纯JavaScript实现HTML5 Canvas 6种特效滤镜

共 11231字,需浏览 23分钟

 ·

2020-07-10 00:12

(给前端大学加星标,提升前端技能.

来源: 

https://www.kancloud.cn/digest/canvas-programming/154008

小试牛刀,实现了六款简单常见HTML5 Canvas特效滤镜,并且封装成一个纯JavaScript可调用的API文件gloomyfishfilter.js。支持的特效滤镜分别为:1.反色2.灰色调3.模糊4.浮雕5.雕刻6.合理滤镜原理解释:2.灰色调:获取一个预期点RGB值r,g,b则新的RGB值newr =(r * 0.272)+(g * 0.534)+(b * 0.131);newg =(r * 0.349)+(g * 0.686)+(b * 0.168);newb =(r * 0.393)+(g * 0.769)+(b * 0.189);3.模糊:基于一个5 * 5的卷积核4.浮雕与雕刻:根据当前预期的前一个预期RGB值与它的后一个重新的RGB值之差再加上1285.总体:模拟了物体在镜子中与之对应的效果。杂项准备1、如何获取Canvas 2d context对象
var canvas = document.getElementById("target");
canvas.width = source.clientWidth;
canvas.height = source.clientHeight;
**if**(!canvas.getContext) {
console.log("Canvas not supported. Please install a HTML5compatible browser.");
**return**;
}
// get 2D context of canvas and draw image
tempContext = canvas.getContext("2d");
2、如何添加一个DOM img对象到Canvas对象中
var source = document.getElementById("source");
tempContext.drawImage(source, 0, 0, canvas.width,canvas.height);
3、如何从Canvas对象中获取预定数据
var canvas = document.getElementById("target");
var len = canvas.width * canvas.height * 4;
var canvasData = tempContext.getImageData(0, 0, canvas.width, canvas.height);
var binaryData = canvasData.data;
4、如何对DOM对象实现鼠标ClickEvent绑定
function bindButtonEvent(element, type, handler) {  
if(element.addEventListener){
element.addEventListener(type, handler,**false**);
}else{
element.attachEvent('on'+type, handler);// for IE6,7,8
}
}
5、如何调用实现的gfilter API完成滤镜功能
 //导入API文件
gfilter.colorInvertProcess(binaryData, len); //调用 API
6、浏览器支持:IE,FF,Chrome上测试通过,其中IE上支持通过以下标签实现:


效果演示:46529b782d098ad6411f66958766afc0.webp应用程序源代码:CSS部分:
#svgContainer {  width:800px;  height:600px;  background-color:#EEEEEE;}
#sourceDiv { float: left; border: 2px solid blue} #targetDiv { float: right;border: 2px solid red}
filter1.html中HTML源代码:
Canvas Filter Demo