A piece of code:

ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(level1, 0, 0); ctx.save(); ctx.fillRect(0,0,mask.width,mask.height); ctx.globalCompositeOperation="source-in"; ctx.drawImage(hero,0,0); ctx.restore(); 

Trying to make a mask for the hero. But it turns out such a glitch.

hero


The structure is as follows:

1) Layer backgorund written in css (we see it).

2) Backgorund level in html5 canvas there forests, grass underfoot (not displayed).

3) Mask for Hero.

4) Hero itself.


Waiting: grass with background and cut out hero.

Reality: the mask works, but cuts backgorund of canvas.

It looks like ctx.globalCompositeOperation = "source-in"; applies to the whole context, not to the added layers. Can you please tell me how to fix it? Maybe you need to draw it all in a separate context?

  • do you have a hero in the original image on a transparent background? if yes, then why do you need to change the "blending modes" at all (I don’t know how to call it correctly) Draw a background, in the standard "source-over" mode, the hero will draw over. is that necessary? or is there another problem? - noadev
  • @noadev, no, not transparent. The fact is that the mask allows you to do more. for example, with the help of her clouds can do. and the usual png will not do that. - Anonymous

1 answer 1

It turned out, everything is very simple. You just had to deal with the state game globalCompositeOperation.

 $(function() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var truck, logo, backgroundlevel; var newColor = "red"; var imageURLs = []; var imagesOK = 0; var imgs = []; imageURLs.push("mask.png"); imageURLs.push("image.jpg"); imageURLs.push("backgorund.jpg"); loadAllImages(); function loadAllImages() { for (var i = 0; i < imageURLs.length; i++) { var img = new Image(); imgs.push(img); img.onload = function() { imagesOK++; imagesAllLoaded(); }; img.src = imageURLs[i]; } } var imagesAllLoaded = function() { if (imagesOK == imageURLs.length) { truck = imgs[0]; logo = imgs[1]; backgroundlevel = imgs[2]; start(); } }; function start() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(logo, 0, 0); ctx.globalCompositeOperation = "destination-in"; ctx.drawImage(truck, 0, 0); ctx.globalCompositeOperation = "destination-over"; ctx.drawImage(backgroundlevel, 0, 0); ctx.globalCompositeOperation = "source-over"; } }); 
 body { background-color: ivory; padding: 20px; } #canvas { border: 1px solid red; } 
 <!doctype html> <html> <head> </head> <body> <canvas id="canvas" width=500 height=253></canvas> </body> </html>