davivid
davivid

Reputation: 5960

canvas - layer small image on larger background image, merge to single canvas pixel data

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

Upvotes: 3

Views: 1849

Answers (1)

pepkin88
pepkin88

Reputation: 2756

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);

Upvotes: 4

Related Questions