最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to move a drawn image on HTML5 canvas? - Stack Overflow

programmeradmin3浏览0评论

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? (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. The problem is that calling toDataUrl() in order to get the final image - is very CPU consuming.

Any other way to achieve this? Why can't i just tell the canvas to 'move everything up / down' by x pixels...?

thanks!

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? (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. The problem is that calling toDataUrl() in order to get the final image - is very CPU consuming.

Any other way to achieve this? Why can't i just tell the canvas to 'move everything up / down' by x pixels...?

thanks!

Share Improve this question asked Sep 8, 2015 at 7:23 Amit KanferAmit Kanfer 411 silver badge5 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

Canvas drawImage() method accept an other canvas as source.
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./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/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData) to get the image data and ctx.putImageData (https://developer.mozilla/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData) to put the image data where you want.

Edit

Kaido's solution is the better alternative though.

Reference

Why is putImageData so slow?

发布评论

评论列表(0)

  1. 暂无评论