Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to implement vertical scrolling of the contents of a HTML5 canvas element. I don't want to render the whole content again. Instead I would like to move the whole content down/up and only render the area, which has been scrolled into view.

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

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

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

like image 984
Fabian Jakobs Avatar asked Jan 11 '10 10:01

Fabian Jakobs


2 Answers

Try this:

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

drawImage can take either an HTMLImageElement, an HTMLCanvasElement, or an HTMLVideoElement for the first argument.

like image 132
Juan Avatar answered Oct 19 '22 02:10

Juan


For absolute speed, I would use an over-sized <canvas> inside a <div> with overflow:hidden set then use regular DOM methods to scroll the <canvas> inside the <div>.

Of course, this sacrifices memory usage in favor of speed.

like image 44
slebetman Avatar answered Oct 19 '22 03:10

slebetman