半透明形状的画布阴影/发光效果?

时间:2017-10-10 02:47:56

标签: html5 canvas

我有一个半透明的形状:

this.cx.beginPath();
this.cx.globalAlpha = .1;
this.cx.fillStyle = gradientFill;
this.cx.strokeStyle = gradientStroke;
this.cx.arc(150, 150, 139, 0, Math.PI * 2, true);
this.cx.lineWidth = 1;
this.cx.stroke();
this.cx.fill();

我想添加一些阴影,但我希望它只出现在形状之外,我想更多的是发光而不是阴影。有没有办法在画布中执行此操作,因为我的尝试:

this.cx.shadowColor = 'rgba(0, 0, 0, .75)';
this.cx.shadowBlur = 5;
this.cx.shadowOffsetX = 5;
this.cx.shadowOffsetY = -5;

看起来很平凡,因为半透明的形状可以看到黑暗的阴影。

谢谢!

1 个答案:

答案 0 :(得分:0)

一种方法是使用globalCompositeOperations以便仅保留外部阴影,然后在其上重绘半透明部分。

但请注意,你会有很多神器噪音......



(async function() {
  var ctx = c.getContext('2d');
  // commons
  var gradientFill = ctx.createLinearGradient(0, 0, 200, 0);
  gradientFill.addColorStop(0, 'rgba(0,0,0,0)')
  gradientFill.addColorStop(1, 'rgba(255,0,0,1)')
  var gradientStroke = ctx.createLinearGradient(0, 0, 200, 0);
  gradientStroke.addColorStop(0, 'rgba(0,0,0,0)')
  gradientStroke.addColorStop(1, 'rgba(0,255,0,1)')
  ctx.lineWidth = 5;
  // needed only once
  ctx.beginPath();
  ctx.arc(150, 150, 139, 0, Math.PI * 2, true);

  await wait(1000); // simply to show each step

  // firt we draw only the shadow with black fill and stroke
  ctx.shadowColor = 'rgba(0, 0, 0, .75)';
  ctx.shadowBlur = 5;
  ctx.shadowOffsetX = 5;
  ctx.shadowOffsetY = -5;
  ctx.stroke();
  ctx.fill();

  await wait(1000);

  // then keep only the shadow
  ctx.globalCompositeOperation = 'destination-out'; // will erase existing content at drawn position
  ctx.shadowColor = 'transparent'; // remove the shadow
  ctx.stroke();
  ctx.fill();

  await wait(1000);
  
  // finally draw the semi-transparent version
  ctx.globalCompositeOperation = 'source-over';
  ctx.globalAlpha = .1;
  ctx.fillStyle = gradientFill;
  ctx.strokeStyle = gradientStroke;
  ctx.stroke();
  ctx.fill();

})();

function wait(t) {
  return new Promise(r => setTimeout(r, t))
}

<canvas id="c" height="300"></canvas>
&#13;
&#13;
&#13;