What is the fastest way to move a rectangular (pixel) area inside an HTML5 canvas element

I want to implement vertical scrolling of the contents of an HTML5 canvas element. I do not want to display all the content again. Instead, I would like to move all the content up / down and display only the area that was scrolled into the window.

I experimented with the getImageData and putImageData , but in my tests they are almost as slow as repainting the entire scene.

 // scroll 20px down var data = ctx.getImageData(0, 0, width, height-20); ctx.putImageData(0, 20); 

What is the fastest way to copy areas of a rectangular pixel inside a canvas element?

+7
javascript html5 canvas
source share
2 answers

Try the following:

 ctx.drawImage(ctx.canvas, 0, 0, width, height-20, 0, 20, width, height-20); 

drawImage can accept either HTMLImageElement , a HTMLCanvasElement , or HTMLVideoElement for the first argument.

+12
source share

For absolute speed, I would use the <canvas> size with the <canvas> size inside the <div> with overflow:hidden , and then use the usual DOM methods to scroll through the <canvas> inside the <div> .

Of course, this sacrifices the use of memory in favor of speed.

+7
source share

All Articles