如何使画布轮廓在悬浮发光时成为透明的png

Mat*_*ood 2 html javascript css jquery canvas

是否可以自动给图像赋予发光效果,例如使用画布?

jsfiddle

canvas标签必须省略透明

透明iphonev

并使其具有外部辉光?

外发光

<canvas id="canvas" width=960 height=960></canvas>
Run Code Online (Sandbox Code Playgroud)

mar*_*rkE 5

通过应用一系列重叠的阴影并增加模糊效果使画布路径发光

演示: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();
Run Code Online (Sandbox Code Playgroud)

要获取电话图像的轮廓路径,可以使用“行进蚂蚁”算法。

该算法将创建轮廓图像的路径。

在您的情况下,您可以将图像定义为所有不透明的像素。

这是出色的d3库中使用的“行军蚁”的一个很好的实现:

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);
Run Code Online (Sandbox Code Playgroud)

使用ctx.getImageData从画布获取像素颜色数组

// grab the image's pixel data

imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
data=imgData.data;
Run Code Online (Sandbox Code Playgroud)

定义一个函数,检查画布上任何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);
}
Run Code Online (Sandbox Code Playgroud)

调用轮廓函数:

// call the marching ants algorithm
// to get the outline path of the image
// (outline=outside path of transparent pixels

var points=geom.contour(defineNonTransparent);
Run Code Online (Sandbox Code Playgroud)

这是一个示例结果:

  • 使用重叠的阴影自动生成光晕

  • 手机的轮廓路径是使用行进蚂蚁算法计算的

在此处输入图片说明