为什么不能使用XOR globalCompositeOperation在画布上拖动矩形?

时间:2011-07-24 13:50:22

标签: javascript html5 canvas

我在画布上创建了很多矩形。现在我要拖动其中一个在画布上移动。如何做到这一点?我找到了一个解决方案:清除画布并重新绘制它。是的,它有效。但如果有10,000个矩形,我需要花很多时间重绘它们。 我是一名C ++程序员。我知道如何使用XOR实现这个功能。我在how to draw rectangle on java applet using mouse drag event找到了一个Java解决方案。为什么Canvas的XOR不能按我的意愿工作?还有其他方法可以实现我的理想吗?感谢。

3 个答案:

答案 0 :(得分:1)

您可以创建包含原始画布图像的隐藏图像(在拖动之前),然后使用保存的图像重绘,因此每次移动时只有一个绘制操作。

//canvas = your canvas element
//Save the image before drag
var img = new Image();
img.src = canvas.toDataURL();

//On drag, redraw the saved image
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);

jsFiddle


或者,如果您知道矩形的宽度和高度,则只能重绘以前矩形的区域:

//Store the rectangle's coordinates
var rectCoords = {x: 0, y: 0};
//The rectangle's size
var rectSize = {width: 50, height: 50};
//Create a canvas element
var savedCanvas = document.createElement("canvas");
savedCanvas.width = canvas.width + rectSize.width;
savedCanvas.height = canvas.height + rectSize.height;
var ctxSaved = savedCanvas.getContext("2d");

在拖动之前:

//Draw the entire canvas onto the saved canvas
ctxSaved.drawImage(canvas, 0, 0);
//Store your coordinates for the redraw
rectCoords.x = "Your coordinate";
rectCoords.y = "Your coordinate";

当您需要重绘矩形时,您只需要执行以下操作:

//Draw original image only in the area where the rectangle was drawn
ctx.drawImage(savedCanvas, rectCoords.x, rectCoords.y, rectSize.width, rectSize.height,
rectCoords.x, rectCoords.y, rectSize.width, rectSize.height);
//Store your coordinates for the next redraw
rectCoords.x = "Your coordinate";
rectCoords.y = "Your coordinate";

请参阅jsFiddle了解工作演示。

注意:出于安全考虑,如果您在另一个域中在画布上绘制了图像,则无法使用此功能。

答案 1 :(得分:0)

如何只控制Canvas上的单个元素。 当您将某些内容绘制到画布上时,API会将“像素”写入画布并忘记关于它的所有内容。

答案 2 :(得分:0)

我不会试图通过XOR来使它工作,它不太合适,因为绘图的“之前”和“之后”都包含你想要移动的矩形。

要开始这一行,请查看我的tutorials on the matter