您可以创建一个包含原始画布图像(拖动前)的隐藏图像,然后使用保存的图像重新绘制,因此每次移动只有一次绘制操作。
//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 以获得工作演示。
注意:出于安全考虑,如果您在画布上绘制了来自其他域的图像,这将不起作用。