我的意思是,用户在 HTML Canvas 上的 xy 点处按下鼠标按钮,按下鼠标按钮时,可以根据固定 xy 点的光标的移动来调整矩形的大小。就像突出显示的工作原理一样。
这是我到目前为止所得到的,但它似乎不起作用:
canvas.addEventListener('mousedown', function(e){
var rectx = e.clientX;
var recty = e.clientY;
canvas.onmousemove = function(e){
var df = e.clientX;
var fg = e.clientY;
};
context.rect(rectx, recty, df-rectx, fg-recty);
context.stroke();
}, false);
最佳答案
假设您的 Canvas 上下文中没有转换(缩放
、翻译
)。
创建可调整大小的矩形的基本步骤如下:
创建一个
<mousedown
监听器,设置一个标志,指示用户按住鼠标按钮,并设置“ anchor ”或初始坐标。创建一个取消设置标志的
mouseup
监听器。创建一个
mousemove
监听器,如果标志指示鼠标已按下,则根据鼠标坐标重新绘制 Canvas ,并更改矩形的大小。
重要的一点是,事件
对象中的客户端坐标是相对于页面的,而不是 Canvas 元素。您经常需要将 clientX
和 clientY
转换为 Canvas 坐标:
var getCanvasCoords = function (clientX, clientY) {
var rect = canvas.getBoundingClientRect();
return {
x: clientX - rect.left,
y: clientY - rect.top
};
};
前两个步骤如下所示:
var anchorX;
var anchorY;
var mouseDown = false;
canvas.addEventListener('mousedown', function (event) {
var coords = getCanvasCoords(event.clientX, event.clientY);
anchorX = coords.x;
anchorY = coords.y;
mouseDown = true;
});
canvas.addEventListener('mouseup', function (event) {
mouseDown = false;
});
以及mousemove
处理程序:
canvas.addEventListener('mousemove', function (event) {
var coords = getCanvasCoords(event.clientX, event.clientY);
var width = coords.x - anchorX;
var height = coords.y - anchorY;
// clear canvas for redrawing
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(anchorX, anchorY, width, height);
});
关于javascript - 如何在 JavaScript 中创建一个可调整大小的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41745072/