原生JavaScript Canvas:创建可拖拽、可缩放矩形
本教程演示如何利用原生JavaScript和Canvas API构建一个可拖动和调整大小的矩形。
一、可拖拽矩形
以下代码实现了可拖拽矩形的绘制:
// 获取画布元素和上下文 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // 矩形对象 let rect = { x: 100, y: 100, width: 50, height: 50, isDragging: false }; // 绘制矩形 function drawRect() { ctx.fillStyle = 'red'; ctx.fillRect(rect.x, rect.y, rect.width, rect.height); } // 鼠标按下事件 canvas.addEventListener('mousedown', (e) => { const mouseX = e.clientX - canvas.offsetLeft; const mouseY = e.clientY - canvas.offsetTop; // 检查鼠标是否在矩形内 if (mouseX >= rect.x && mouseX <= rect.x + rect.width && mouseY >= rect.y && mouseY <= rect.y + rect.height) { rect.isDragging = true; } }); // 鼠标移动事件 canvas.addEventListener('mousemove', (e) => { if (rect.isDragging) { const mouseX = e.clientX - canvas.offsetLeft; const mouseY = e.clientY - canvas.offsetTop; rect.x = mouseX - rect.width / 2; rect.y = mouseY - rect.height / 2; ctx.clearRect(0, 0, canvas.width, canvas.height); drawRect(); } }); // 鼠标松开事件 canvas.addEventListener('mouseup', () => { rect.isDragging = false; }); drawRect();
二、调整矩形大小
扩展上述代码,实现点击矩形边缘调整大小的功能:
// ... (previous code) ... // 鼠标点击事件 canvas.addEventListener('click', (e) => { const mouseX = e.clientX - canvas.offsetLeft; const mouseY = e.clientY - canvas.offsetTop; // 检查鼠标是否在矩形边缘附近 (简化版,仅处理右下角缩放) if (mouseX >= rect.x + rect.width - 5 && mouseX <= rect.x + rect.width + 5 && mouseY >= rect.y + rect.height - 5 && mouseY <= rect.y + rect.height + 5) { rect.isResizing = true; } }); canvas.addEventListener('mousemove', (e) => { if (rect.isResizing) { const mouseX = e.clientX - canvas.offsetLeft; const mouseY = e.clientY - canvas.offsetTop; rect.width = mouseX - rect.x; rect.height = mouseY - rect.y; ctx.clearRect(0, 0, canvas.width, canvas.height); drawRect(); } }); canvas.addEventListener('mouseup', () => { rect.isResizing = false; }); // ... (rest of the code) ...
高级库推荐
Fabric.js是一个功能强大的Canvas库,提供更便捷的图形操作和事件处理。 它能简化很多复杂操作,例如更精确的缩放和旋转控制。 如果您需要更高级的功能,Fabric.js是一个值得考虑的选择。
请注意,以上代码是一个简化版本,仅演示基本原理。 实际应用中,可能需要更精细的碰撞检测和边界处理。 完整的可调整大小的矩形实现需要处理所有八个边角的缩放,以及防止矩形尺寸小于0的情况。