怎么用canvas实现图片滤镜效果

小编给大家分享一下怎么用canvas实现图片滤镜效果,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

专注于为中小企业提供成都做网站、网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业永清免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了1000多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

1.获取图像数据

img.src = ’/upload/otherpica43/19974.jpg’;

canvas.width = img.width;

canvas.height = img.height;

var context = canvas.getContext(“2d”);

context.drawImage(img, 0, 0);

var canvasData = context.getImageData(0, 0, canvas.width, canvas.height);

2.设置过滤矩阵

var m_VideoType=0;

var pattern=new Array();

switch (m_VideoType)

{

case0://VIDEO_TYPE.VIDEO_STAGGERED:

{

pattern = [

0, 1,

0, 2,

1, 2,

1, 0,

2, 0,

2, 1,

];

break;

}

case1://VIDEO_TYPE.VIDEO_TRIPED:

{

pattern = [

0,

1,

2,

];

break;

}

case2://VIDEO_TYPE.VIDEO_3X3:

{

pattern =

[

0, 1, 2,

2, 0, 1,

1, 2, 0,

];

break;

}

default:

{

pattern =

[

0, 1, 2, 0, 0,

1, 1, 1, 2, 0,

0, 1, 2, 2, 2,

0, 0, 1, 2, 0,

0, 1, 1, 1, 2,

2, 0, 1, 2, 2,

0, 0, 0, 1, 2,

2, 0, 1, 1, 1,

2, 2, 0, 1, 2,

2, 0, 0, 0, 1,

1, 2, 0, 1, 1,

2, 2, 2, 0, 1,

1, 2, 0, 0, 0,

1, 1, 2, 0, 1,

1, 2, 2, 2, 0,

];

break;

}

}

var pattern_width = [ 2, 1, 3, 5 ];

var pattern_height = [6, 3, 3, 15 ];

3.获取过滤数据

for ( var x = 0; x < canvasData.width; x++) {

for ( var y = 0; y < canvasData.height; y++) {

// Index of the pixel in the array

var idx = (x + y * canvasData.width) * 4;

var r = canvasData.data[idx + 0];

var g = canvasData.data[idx + 1];

var b = canvasData.data[idx + 2];

var nWidth = pattern_width[m_VideoType];

var nHeight = pattern_height[m_VideoType];

var index = nWidth * (y % nHeight) + (x % nWidth);

index = pattern[index];

if (index == 0)

var r = fclamp0255(2 * r);

if (index == 1)

var g = fclamp0255(2 * g);

if (index == 2)

var b = fclamp0255(2 * b);

// assign gray scale value

canvasData.data[idx + 0] = r; // Red channel

canvasData.data[idx + 1] = g; // Green channel

canvasData.data[idx + 2] = b; // Blue channel

canvasData.data[idx + 3] = 255; // Alpha channel

// 加上黑色的边框

if(x < 8 || y < 8 || x > (canvasData.width - 8) || y > (canvasData.height - 8))

{

canvasData.data[idx + 0] = 0;

canvasData.data[idx + 1] = 0;

canvasData.data[idx + 2] = 0;

}

}

}

4.写入过滤后的数据

context.putImageData(canvasData, 0, 0);

以上是“怎么用canvas实现图片滤镜效果”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!


文章名称:怎么用canvas实现图片滤镜效果
分享链接:http://scyanting.com/article/iihhpd.html