简体   繁体   English

如何在 HTML5 画布上移动绘制的图像?

[英]How to move a drawn image on HTML5 canvas?

Assuming i have an HTML5 canvas on which i've already drawn multiple images, and i don't have the final resulting image "in hand", and now i want to move the whole image in the canvas up?假设我有一个 HTML5 画布,我已经在其上绘制了多个图像,并且我没有“手头”最终生成的图像,现在我想将画布中的整个图像向上移动? (just if like the user chose to 'scroll down' the image) (就像用户选择“向下滚动”图像一样)

If i had the final image, i could have clear the canvas and draw it again in a 'y' coordinate which is negative, that'll work.如果我有最终图像,我可以清除画布并在负的“y”坐​​标中再次绘制它,这会起作用。 The problem is that calling toDataUrl() in order to get the final image - is very CPU consuming.问题是调用 toDataUrl() 以获得最终图像 - 非常消耗 CPU。

Any other way to achieve this?任何其他方式来实现这一目标? Why can't i just tell the canvas to 'move everything up / down' by x pixels...?为什么我不能告诉画布将所有东西向上/向下移动 x 像素......?

thanks!谢谢!

Canvas drawImage() method accept an other canvas as source. Canvas drawImage()方法接受另一个画布作为源。
You can also draw the canvas on itself, but at each iteration, your image will have changed.您也可以在画布本身上绘制画布,但在每次迭代中,您的图像都会发生变化。

So the easiest way is to create an other canvas, which will keep your actual canvas image, and draw this new canvas to the one in the document :因此,最简单的方法是创建另一个画布,它将保留您的实际画布图像,并将此新画布绘制到文档中的画布上:

 var canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), img = new Image(), // a ghost canvas that will keep our original image gCanvas = document.createElement('canvas'), gCtx = gCanvas.getContext('2d'); gCanvas.width = canvas.width; gCanvas.height = canvas.height; img.onload = function() { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); gCtx.drawImage(canvas, 0, 0, canvas.width, canvas.height); requestAnimationFrame(moveUp); } img.src = "http://lorempixel.com/200/200"; var y = 0; function moveUp() { if (--y < (canvas.height * -0.5)) return; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(gCanvas, 0, y, canvas.width, canvas.height); requestAnimationFrame(moveUp) }
 <canvas width=200 height=200></canvas>

You can use ctx.getImageData ( https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData ) to get the image data and ctx.putImageData ( https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData ) to put the image data where you want.您可以使用ctx.getImageData ( https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData ) 来获取图像数据和ctx.putImageData ( https://developer.mozilla.org /en-US/docs/Web/API/CanvasRenderingContext2D/putImageData ) 将图像数据放在您想要的位置。

Edit编辑

Kaido's solution is the better alternative though.不过,凯多的解决方案是更好的选择。

Reference参考

Why is putImageData so slow? 为什么 putImageData 这么慢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM