用canvas实现图片滤镜效果详解之视频效果

这是一个很有意思的特效,模拟摄像机拍摄电视屏幕画面时出现点状颗粒的效果。颗粒的大小通过变换矩阵实现,可以任意调节,有兴趣研究的朋友可以尝试更多的效果,代码没有经过优化,只是一个粗糙的Demo,大家可以自行改进。

创新互联主要从事网站建设、成都网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务卫东,十余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575

1.获取图像数据
1
2
3
4
5
6
img.src = ’http://bloglaotou.duapp.com/wp-content/themes/frontopen2/tools/filter/p_w_picpath3.jpg’;
canvas.width = img.width;
canvas.height = img.height;
varcontext = canvas.getContext(“2d”);
context.drawImage(img, 0, 0);
varcanvasData = context.getImageData(0, 0, canvas.width, canvas.height);

2.设置过滤矩阵
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
varm_VideoType=0;
varpattern=newArray();
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;
}
}
varpattern_width = [ 2, 1, 3, 5 ];
varpattern_height = [6, 3, 3, 15 ];

3.获取过滤数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
for( varx = 0; x < canvasData.width; x++) {
for( vary = 0; y < canvasData.height; y++) {
// Index of the pixel in the array
varidx = (x + y * canvasData.width) * 4;
varr = canvasData.data[idx + 0];
varg = canvasData.data[idx + 1];
varb = canvasData.data[idx + 2];
varnWidth = pattern_width[m_VideoType];
varnHeight = pattern_height[m_VideoType];
varindex = nWidth * (y % nHeight) + (x % nWidth);
index = pattern[index];
if(index == 0)
varr = fclamp0255(2 * r);
if(index == 1)
varg = fclamp0255(2 * g);
if(index == 2)
varb = 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.写入过滤后的数据
1
context.putImageData(canvasData, 0, 0);

5.效果预览

点击这里预览

5.参考资料

代震军ImageFilter开源项目


文章名称:用canvas实现图片滤镜效果详解之视频效果
当前URL:http://myzitong.com/article/goojjh.html