如何显示用户矩形的外观?

时间:2013-07-03 23:52:18

标签: javascript jquery canvas html5-canvas rectangles

我正试图在画布上绘制一个矩形,只需点击一下,鼠标移动,再点击一下。在第一次单击后,我应该如何跟随用户的光标,并在画布上显示填充矩形的预览,显示在任何给定坐标处的形状。

到目前为止,我可以成功创建矩形而不显示矩形在任何坐标处的样子。

以下是目前的代码:

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/)中看到的那样,但我不确定如何将其与现有代码连接。

1 个答案:

答案 0 :(得分: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);
});

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