Fabian Jakobs Fabian Jakobs - 1 year ago 140
HTML Question

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download