您不能将 CSS 应用于绘制到画布上的形状,但您可以简单地使用阴影来创建发光效果。
A demo here
var canvas = document.getElementById('canvas'), // canvas
ctx = canvas.getContext('2d'), // context
w = canvas.width, // cache some values
h = canvas.height,
cx = w * 0.5,
cy = h * 0.5,
glow = 0, // size of glow
dlt = 1, // speed
max = 40; // max glow radius
ctx.shadowColor = 'rgba(100, 100, 255, 1)'; // glow color
ctx.fillStyle = '#fff'; // circle color
function anim() {
ctx.clearRect(0, 0, w, h); // clear frame
ctx.shadowBlur = glow; // set "glow" (shadow)
ctx.beginPath(); // draw circle
ctx.arc(cx, cy, cx * 0.25, 0, 6.28);
ctx.fill(); // fill and draw glow
glow += dlt; // animate glow
if (glow <= 0 || glow >= max) dlt = -dlt;
requestAnimationFrame(anim); // loop
}
anim();
更新
要获得具有外发光的轮廓,您只需使用复合操作“打孔”圆心即可。这里的示例使用保存/恢复来移除阴影 - 您可以通过手动重置这些来优化代码 - 但为简单起见,请进行以下修改:
ctx.fillStyle = '#fff';
// remove shadow from global
function anim() {
ctx.clearRect(0, 0, w, h);
// draw main circle and glow
ctx.save(); // store current state
ctx.shadowColor = 'rgba(100, 100, 255, 1)';
ctx.shadowBlur = glow;
ctx.beginPath();
ctx.arc(cx, cy, cx * 0.25, 0, 6.28);
ctx.fill();
ctx.restore(); //restore -> removes the shadow
// draw inner circle
ctx.globalCompositeOperation = 'destination-out'; // removes what's being drawn
ctx.beginPath();
ctx.arc(cx, cy, cx * 0.23, 0, 6.28); // smaller filled circle
ctx.fill();
ctx.globalCompositeOperation = 'source-over'; // reset
glow += dlt;
if (glow <= 0 || glow >= max) dlt = -dlt;
requestAnimationFrame(anim);
}
复合操作将从下一次绘制操作中移除像素。只需在顶部画一个较小的实心圆圈,即可留下第一个圆圈的轮廓及其发光。
Modified fiddle here