我正在尝试通过单击、鼠标移动和再次单击在画布上绘制一个矩形。我应该如何在第一次单击后跟随用户的光标并在画布上显示填充矩形的预览,该矩形在任何给定坐标处的形状是什么样的。
到目前为止,我可以成功创建矩形,而无需显示矩形在任何坐标处的外观。
这是到目前为止的代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX;
var startY;
var drawingShape = false;
//function getMousePos(canvas, ev) {
//var rect = canvas.getBoundingClientRect();
//}
//canvas.addEventListener('mousemove', function (ev) {
//var mousePos = getMousePos(canvas, ev);
//}
function setMousePosition(e) {
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
$("#downlog").html("Down: " + mouseX + " / " + mouseY);
if (drawingShape) {
drawingShape = false;
ctx.beginPath();
ctx.fillStyle = "#FF0000";
ctx.rect(startX, startY, mouseX - startX, mouseY - startY);
ctx.fill();
} else {
drawingShape = true;
startX = mouseX;
startY = mouseY;
}
}
$("#canvas").mousedown(function (e) {
setMousePosition(e);
});
正如我在本 HTML5 教程 ( http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ )中看到的那样,我尝试使用事件侦听器来移动鼠标,但我不确定如何连接它与现有代码。