问题描述
之前我见过这个问题,但给出的答案是通过路径绘制的画布图像,但我正在绘制图像。
I've seen this question before but the answers given are for canvas images that have been drawn on via path however, i'm drawing an image.
是可以创建插入阴影
?
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 10;
context.shadowColor = 'rgba(30,30,30, 0.4)';
var imgOne = new Image();
imgOne.onload = function() {
context.drawImage(imgOne, 0, 0);
};
imgOne.src = "./public/circle.png";
所以我画圆圈图片。我现在在圆圈的外面有一个小阴影,我怎么能得到这个插入
而不是 offset
?
So I draw the circle picture on. I've now at the moment got a slight shadow on the outside of the circle, how can I get this inset
instead of offset
?
推荐答案
画布将遮挡图像从不透明变为透明的位置,正如K3N在其正确答案中所示,你可以将图像从里面翻出来(不透明变得透明,反之亦然),这样就可以在圆圈内绘制阴影。
Canvas will shadow where an image changes from opaque to transparent so, as K3N shows in his correct answer, you can turn the image inside out (opaque becomes transparent & visa-versa) so the shadows are drawn inside the circle.
如果您知道圆的中心点和半径,则可以使用描边路径创建插入圆阴影。这是一个例子:
If you know your circle's centerpoint and radius, you can use a stroked-path to create an inset circle shadow. Here's an example:
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
context.beginPath();
context.arc(cw/2,ch/2,75,0,Math.PI*2);
context.fillStyle='lightcyan';
context.fill();
context.globalCompositeOperation='source-atop';
context.shadowOffsetX = 500;
context.shadowOffsetY = 0;
context.shadowBlur = 15;
context.shadowColor = 'rgba(30,30,30,1)';
context.beginPath();
context.arc(cw/2-500,ch/2,75,0,Math.PI*2);
context.stroke();
context.stroke();
context.stroke();
context.globalCompositeOperation='source-over';
<canvas id="canvas" width=300 height=300></canvas>
如果您的路径不规则或难以定义在数学上,您还可以使用边缘路径检测算法。一种常见的边路径算法是。 Stackoverflow的K3N编写了一个很好的。
If your path is irregular or hard to define mathematically, you can also use edge-path detection algorithms. One common edge-path algorithm is Marching Squares. Stackoverflow's K3N has coded a nice Marching Squares algorithm.
这篇关于HTML5画布图像上的插入阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!