views:

45

answers:

1

How do I merge a smaller image on top of a larger background image on one canvas. The smaller image will move around. So I will need to keep reference of the original background pixel data, so that the each frame the canvas can be redrawn, with the overlay in its new position.

BgImage: 1280 x 400, overlayImage: 320 x 400, overlayOffsetX: mouseX

+2  A: 

I think it is common to draw whole scene each time you want to change something, so:

context.drawImage(bgImage, 0, 0);
context.drawImage(overlayImage, overlayOffsetX, 0);

UPDATE

You could manually compose image data of two images with making copy of background image data

or

do something easier, probably faster. You could create new canvas element (without attaching to the document) which would store image data in easy to manage form. putImageData is good if you want to place rectangular image into the canvas. But if you want to put image with transparency, additional canvas will help. See if example below is satisfying you.

// preparation of canvas containing data of overlayImage
var OVERLAY_IMAGE_WIDTH = 320;
var OVERLAY_IMAGE_Height = 400;
var overlayImageCanvas = document.createElement('canvas');
overlayImageCanvas.width = OVERLAY_IMAGE_WIDTH;
overlayImageCanvas.height = OVERLAY_IMAGE_HEIGHT;
overlayImageCanvas.getContext('2d').putImageData(overlayImage, 0, 0);

// drawing scene, execute this block every time overlayOffsetX has changed
context.putImageData(bgImage, 0, 0);
context.drawImage(overlayImageCanvas, overlayOffsetX, 0);
pepkin88
I have two sets of pixel data obtained from these two images using getImageData. so my overlay data is much smaller and I need to place this over the background data at a certain position, this can be placed on the canvas using putImageData for the whole large combined image - but my understanding is that first these two need to be merged?
davivid
that worked really well! and seems very fast, I didnt realise you could do it this way seems very useful. thanks
davivid