【问题标题】:Why can't drag a rectangle on canvas using the XOR globalCompositeOperation?为什么不能使用 XOR globalCompositeOperation 在画布上拖动矩形?
【发布时间】:2011-07-25 14:44:25
【问题描述】:

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

【问题讨论】:

  • 我需要更多建议,谢谢。

标签: javascript html canvas


【解决方案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 以获得工作演示。

注意:出于安全考虑,如果您在画布上绘制了来自其他域的图像,这将不起作用。

【讨论】:

  • drawImage 会消耗大量 CPU,但总比重绘所有形状要好。
  • 您也可以只重绘画布的特定部分(矩形所在的位置) - 这应该会减少 CPU 消耗。
  • 是的。这就是我正在做的。但是算法会很复杂。
【解决方案2】:

没有办法只控制 Canvas 上的单个元素。 当您在画布上绘制某些东西时,API 只会将“像素”写入画布并忘记它的一切。

【讨论】:

    【解决方案3】:

    我不会试图用 XOR 来让它工作,它不是很合适,因为绘图的“之前”和“之后”都包括你想要移动的矩形。

    要开始这条路线,请查看我的tutorials on the matter

    【讨论】:

    • 是的,你的演示没问题。但是效率低下。我有很多形状需要重绘。我无法按时间刷新画布。它将使 CPU 100%。
    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    相关资源
    最近更新 更多