向 Canvas 元素添加阴影(保持元素透明)

Add shadow to Canvas element (keeping the element transparent)

我的 HTML5 canvas 中有一个圆形。我想给它一个阴影样式但不显示描边,所以描边应该是 0 并且阴影:可见。

这是我的代码:

context.beginPath();
context.lineWidth = 5;
context.shadowColor = 'black';
context.strokeStyle = "rgba(255,0,0,1)";
context.shadowBlur = 10;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.arc(x, y, 45, 0, 2 * Math.PI, false);
context.stroke();
context.restore();
context.save();

我在网上找到了类似的方法,但是没有用,老实说我不明白。

context.beginPath();
context.lineWidth = 10;
RGraph.setShadow({'context': context}, 'black', 0, 0, 15)
context.arc(mouseXY[0], mouseXY[1], radius + 5, 0, 2 * Math.PI, false);
context.stroke();

有什么想法可以让不可见的形状有阴影吗?

使用createRadialGradienthttps://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.createRadialGradient

CanvasGradient ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);

var context = canvas.getContext("2d");
var x=80, y=80;
var rg = context.createRadialGradient(x, y, 35, x, y, 45);
rg.addColorStop(0, 'rgba(0,0,0,0.4)');
rg.addColorStop(1, 'rgba(0,0,0,0)');

context.strokeStyle = rg;
context.beginPath();
context.arc(x, y, 40, 2 * Math.PI, false);
context.lineWidth = 10;
context.stroke();
context.restore();
<canvas id="canvas"></canvas>

一个简单的技巧是移动上下文,使笔划在屏幕外,并将阴影移回正确的位置。

简单!

var context = canvas.getContext("2d");

var x= 60, y=60, r=40;

var trickShift = { x:10000, y:1000} ;

context.save();
context.beginPath();
context.translate(-trickShift.x, -trickShift.y);
context.lineWidth = 5;
context.shadowColor = 'black';
context.strokeStyle = '#000'; "transparent";
context.shadowBlur = 15;
context.shadowOffsetX = trickShift.x + 100;
context.shadowOffsetY = trickShift.y + 100;
context.arc(x-100, y-100, r, 0, 2 * Math.PI, false);
context.stroke();
context.restore();
<canvas id="canvas"></canvas>