简体   繁体   中英

HTML5 canvas:Is there a way to use multiple shadows on image?

I'm trying to add some visual effect on my character. https://i.stack.imgur.com/LPSvT.png

As you can see, it have multiple shadows follow.

I use the following code:

context.shadowColor = 'rgba(180,0,0,0.6)';
context.shadowOffsetX = -20;
context.shadowOffsetY = 0;
context.shadowBlur = 3;

context.shadowColor = 'rgba(180,0,0,0.6)';
context.shadowOffsetX = -40;
context.shadowOffsetY = 0;
context.shadowBlur = 3;

context.drawImage(img, x, y, width, height, dx, dy, width, height);

but only the last shadowColor works. Is there a way to use multiple shadows with canvas? Am I going the right way? If not, what is the common way to achieve that? Please, Any help would be appreciated.

You could do it by drawing every time your image, with a new shadow set, but this will get dirty since you'd also draw the original image over and over, plus, shadows are computationally heavy, so don't do it.

Instead, you could compute your shadow on an off-screen canvas before-hand, and only render this canvas on the main one, where you'd like your shadows to appear.

 var img = new Image(); img.onload = init; img.src = "https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png"; var w, h; var ctx = c.getContext('2d'); ctx.imageSmoothingEnabled = ctx.mozImageSmoothingEnabled = ctx.msImageSmoothingEnabled = ctx.webkitImageSmoothingEnabled = false; var shadowCan = c.cloneNode(); shadowCtx = shadowCan.getContext('2d'); function init() { w = shadowCan.width = img.width; h = shadowCan.height = img.height; w *= 1.5; // my image is a bit small for the demo h *= 1.5; // init the shadow once shadowCtx.globalCompositeOperation = 'source-over'; shadowCtx.fillStyle = "red"; shadowCtx.fillRect(0, 0, c.width, c.height); shadowCtx.globalCompositeOperation = 'destination-in'; shadowCtx.drawImage(img, 0, 0); // Now, every non-transparent pixels of our image is red draw(); } function draw() { var maxX = (c.width - w * 2); for (var x = 0; x < maxX; x += w / 2) { // simply change the alpha at each iteration ctx.globalAlpha = (w / maxX) * (x / w); ctx.drawImage(shadowCan, x, 20, w, h); // draw the shadows } ctx.globalAlpha = 1; // reset the alpha ctx.drawImage(img, x, 20, w, h); // draw our original image } 
 canvas { background: pink; } 
 <canvas id="c"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM