通过应用一系列逐渐模糊的重叠阴影,使画布路径发光
演示:http://jsfiddle.net/m1erickson/Z3Lx2/ http://jsfiddle.net/m1erickson/Z3Lx2/
您可以通过改变叠加数量和模糊大小来更改发光样式。
发光效果的示例代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// glow
var glowColor="blue";
ctx.save();
ctx.strokeStyle = glowColor;
ctx.shadowColor = glowColor;
ctx.shadowOffsetX=300;
for (var i = 0; i < 10; i++) {
ctx.shadowBlur = i * 2;
ctx.strokeRect(-270, 30, 75, 150);
}
ctx.restore();
要获取手机图像的轮廓路径,可以使用“行进蚂蚁”算法。
该算法将创建一条勾勒出图像轮廓的路径。
在您的情况下,您可以将图像定义为所有不透明的像素。
下面是优秀的 d3 库中使用的“行进蚂蚁”的一个非常好的实现:
https://github.com/d3/d3-plugins/blob/master/geom/contour/contour.js https://github.com/d3/d3-plugins/blob/master/geom/contour/contour.js
它的使用方式如下:
在画布上绘制您的手机图像。
// draw the image
// (this time to grab the image's pixel data
ctx.drawImage(img,0,0);
使用 ctx.getImageData 从画布获取像素颜色数组
// grab the image's pixel data
imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
data=imgData.data;
定义一个函数,用于检查像素数组中画布上任意 x,y 处的非透明像素。
// This is used by the marching ants algorithm
// to determine the outline of the non-transparent
// pixels on the image
var defineNonTransparent=function(x,y){
var a=data[(y*cw+x)*4+3];
return(a>20);
}
调用轮廓函数:
// call the marching ants algorithm
// to get the outline path of the image
// (outline=outside path of transparent pixels
var points=geom.contour(defineNonTransparent);
这是一个示例结果:
使用重叠阴影自动生成辉光
使用行进蚂蚁算法计算手机的轮廓路径