1

我正在尝试通过单击、鼠标移动和再次单击在画布上绘制一个矩形。我应该如何在第一次单击后跟随用户的光标并在画布上显示填充矩形的预览,该矩形在任何给定坐标处的形状是什么样的。

到目前为止,我可以成功创建矩形,而无需显示矩形在任何坐标处的外观。

这是到目前为止的代码:

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/ )中看到的那样,我尝试使用事件侦听器来移动鼠标,但我不确定如何连接它与现有代码。

4

1 回答 1

0

您可以在开始绘图时存储图像并在每次要编辑时重新加载它。
这是我基于您的代码的快速实现,它需要一些优化(也许只捕获您计划绘制的区域):

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;
var oldImage;

canvas.addEventListener('mousemove', function(e){
  if(drawingShape){
    ctx.putImageData(oldImage,0,0);
    mouseX = parseInt(e.clientX - offsetX, 10);
    mouseY = parseInt(e.clientY - offsetY, 10);

    ctx.beginPath();
    ctx.fillStyle = "#FF0000";
    ctx.rect(startX, startY, mouseX - startX, mouseY - startY);
    ctx.fill();
  }
});

function setMousePosition(e) {
mouseX = parseInt(e.clientX - offsetX, 10);
mouseY = parseInt(e.clientY - offsetY, 10);
$("#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;
    oldImage = ctx.getImageData(0,0,canvas.width,canvas.height);
  }
}

$("#canvas").mousedown(function (e) {
    setMousePosition(e);
});

注意我们如何在鼠标按下事件中存储图像数据并在每次鼠标移动时检索它

于 2013-07-04T00:33:13.770 回答