在HTML5画布中,如何在不影响阴影颜色alpha的情况下更改笔划alpha?

时间:2013-09-23 23:43:37

标签: canvas shadow

我正在尝试在the example found here之后绘制内部阴影。我试图稍微修改它以使笔划完全透明,例如:

ctx.strokeStyle = 'rgba(0, 0, 0, 0.0)';

然而,这导致我的阴影alpha也变为0.0,尽管事实上我也定义了这一行:

ctx.shadowColor = 'rgba(0, 0, 0, 1.0)';

是否有一种方法可以强制阴影的alpha保持在1.0,尽管描边样式为0.0?我不希望显示笔画,我只想要显示阴影。

1 个答案:

答案 0 :(得分:2)

诀窍是偏移形状,使形状位于画布外部和阴影内。

这样我们就不需要考虑原始形状的颜色了 - 或者 - 如果我们希望它部分透明,我们可以复制路径并在后面绘制。

例如:

var offset = 1000;

/// to keep original points of shape we just translate
ctx.translate(-offset, 0);

/// create some shape, here a line
ctx.moveTo(10, 10);
ctx.lineTo(400, 300);
ctx.lineWidth = 5;

/// define shadow, KEY: offset X shadow (or y if prefered=
ctx.shadowOffsetX = offset;
ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.shadowBlur = 16;

/// draw the shape
ctx.stroke();

/// translate back, or use save/restore
ctx.translate(offset, 0);

<强> ONLINE DEMO HERE