FabricJS Filter Template
by codingdude
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js"></script>
<canvas width="600" height="400" id="c"></canvas>
<img style="display:none" src="https://images.unsplash.com/photo-1534809027769-b00d750a6bac?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjU1MjA5fQ&w=2333.3333333333&name=unsplash-Model - Kenagonio https://www.instagram.com/kenagonio/
Photographer - Judeus Samson https://www.instagram.com/judeus.samson.jpg" id="my-image" crossorigin="anonymous">
JavaScript
/*FabricJS Plugin Template*/
fabric.textureSize = 4096;//for filters on large images
/*
options:
filterName - name of the filter
mainParameter - main parameter name
fragmentSource - code for the fragment shader
uniforms
sendUniformData(gl,uniformLocations)
*/
function setupFilter(options){
fabric.Image.filters[options.filterName] = fabric.util.createClass(fabric.Image.filters.BaseFilter, Object.assign({
type: options.filterName,
applyTo2d: function(options) {
alert("This filter only works on browsers that support webgl");
},
getUniformLocations: function(gl, program) {
return options.uniforms(gl,program);
},
createTexture: function(backend, image) {
return backend.getCachedTexture(image.cacheKey, image._element);
},
sendUniformData: function(gl, uniformLocations) {
options.sendUniformData(gl, uniformLocations);
},
isNeutralState:function(){
return false;//this.callSuper('isNeutralState');
}
},options));
fabric.Image.filters[options.filterName].fromObject = fabric.Image.filters.BaseFilter.fromObject;
}
////////////Template end////////////////////
//init filter from template
var options={
filterName: "Histogram",
mainParameter: "channel",
uniforms:function(gl,program){console.log(gl.getAttribLocation(program,'uTest'));return {uChannel:gl.getUniformLocation(program, 'uChannel')};},
sendUniformData:function(gl,uniformLocations){
gl.uniform1f(uniformLocations.uChannel, this.channel);
},
fragmentSource: `
precision highp float;
uniform sampler2D uTexture;
varying vec2 vTexCoord;
uniform float uChannel;
float uTest;
void main() {
vec4 color = texture2D( uTexture, vTexCoord);
uTest = 1.0;
gl_FragColor = vec4(color.rgb,1.0);
}
`
}
setupFilter(options);
//end init filter
var canvas = new fabric.Canvas('c');
var imgElement =...