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

时间:2015-01-18 02:39:43

标签: javascript css html5 canvas

我的HTML5画布中有一个圆圈形状。我想给它一个阴影样式,但是没有显示行程,所以它应该是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();

任何想要为隐形的形状留下阴影的想法?

2 个答案:

答案 0 :(得分:1)

使用createRadialGradient https://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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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

简单!

&#13;
&#13;
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();
&#13;
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;