阴影受到alpha
的影响我有问题如何在不影响阴影的情况下设置alpha?
我尝试在绘制矩形后重置alpha但不使用..
var ctx = document.getElementsByTagName("canvas")[0].getContext("2d");
ctx.shadowColor = "#F08"
ctx.shadowBlur = 10;
ctx.globalAlpha = 0.3;
ctx.rect(10, 10, 60, 60);
ctx.stroke();
ctx.globalAlpha = 1;

<canvas style="border: 1px solid gray;"></canvas>
&#13;
答案 0 :(得分:2)
使用strokeStyle
属性,或fillStyle
如果绘制填充形状。例如:
var ctx = document.getElementsByTagName("canvas")[0].getContext("2d");
var offset = 1000;
ctx.save();
ctx.translate(-offset, 0);
ctx.shadowOffsetX = offset;
ctx.shadowColor = "#F08";
ctx.shadowBlur = 10;
ctx.rect(10, 10, 60, 60);
ctx.stroke();
ctx.restore();
ctx.strokeStyle = "rgba(0,0,0,0.3)";
ctx.rect(10, 10, 60, 60);
ctx.stroke();
&#13;
<canvas style="border: 1px solid gray;"></canvas>
&#13;
答案 1 :(得分:1)
要做到这一点,你需要在3遍中绘制你的形状:
但是为了使第2步正常工作,我们必须考虑x - lineWidth和x + linewidth之间的笔划重叠,从而创建一个lineWidth设置为1的抗锯齿。为了对抗它,我们可以将整个上下文翻译为0.5 px在两个轴上。
var ctx = document.getElementsByTagName("canvas")[0].getContext("2d");
draw();
async function draw() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
if (waiter.checked) await wait(500);
// we need to translate by 0.5 for the stroke to not be antialiased
ctx.setTransform(1, 0, 0, 1, 0.5, 0.5);
// first pass with shadow
ctx.shadowColor = "#F08"
ctx.shadowBlur = 10;
ctx.rect(10, 10, 60, 60);
ctx.stroke();
if (waiter.checked) await wait(1000);
// second pass to clear the stroke
ctx.globalCompositeOperation = 'destination-out';
ctx.shadowColor = "rgba(0,0,0,0)"; // remove shadow
ctx.shadowBlur = 0;
ctx.stroke();
if (waiter.checked) await wait(1000);
// third pass to draw the low alpha stroke
ctx.globalCompositeOperation = 'source-over';
ctx.globalAlpha = 0.1;
ctx.stroke();
// reset to default
ctx.globalAlpha = 1;
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
function wait(t) {
return new Promise(r => setTimeout(r, t));
}
waiter.onchange = draw;
<label> wait between draw steps<input type="checkbox" id="waiter"></label>
<canvas style="border: 1px solid gray;"></canvas>