我正在尝试为我的角色添加一些视觉效果。 https://i.stack.imgur.com/LPSvT.png
如您所见,它会有多个阴影。
我使用以下代码:
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);
但只有最后一个shadowColor有效。 有没有办法在画布上使用多个阴影? 我走对了路吗?如果没有,实现这一目标的常用方法是什么? 请,任何帮助将不胜感激。
答案 0 :(得分:0)
你可以通过每次你的图像绘制一个新的阴影设置,但这会变脏,因为你还要反复绘制原始图像,此外,阴影计算量很大,所以不要这样做它
相反,您可以预先在屏幕外的画布上计算阴影,并且只在主要阴影上渲染此画布,您希望阴影出现在那里。
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>