使用JavaScript为画布创建过滤器

时间:2015-07-13 01:43:28

标签: javascript html5 canvas

我正在创建一个具有绘图功能的插件,我想添加一个过滤器按钮。现在,当从下拉列表中选择“灰度”选项时,将调用名为filterImage的函数。代码中显示的make_base函数只是将图像加载到画布中。目前,图像显示在画布中,但未应用灰度。我该怎么做呢?可以在同一个函数中调用make_base函数(放入图像)和灰度滤镜函数吗?

var canvas = document.getElementById("art-board");
var context = canvas.getContext("2d");
var selectObj = document.getElementById("filter");
var index = selectObj.selectedINdex;
var filter = selectObj[index].value;
make_base(canvas, context);

if(filter=="grayscale"){
    filterImage(canvas, context);
}

function filterImage(canvas, context){

     imageData = context.getImageData(0, 0, canvas.width, canvas.height),
     data = imageData.data,
     iLen = data.length;

      for (i = 0; i < iLen; i+=4) {
        avg = 0.3  * data[i] + 0.59 * data[i + 1] + 0.11 * data[i + 2];
        data[i] = avg + 100;
        data[i + 1] = avg + 50;
        data[i + 2] = avg + 255;
      }

      context.putImageData(imageData, 0, 0);    

 }

1 个答案:

答案 0 :(得分:0)

不是100%肯定,但我认为你的循环存在问题。 I found working RGB values/code on HTML5Rocks

var r = d[i];
var g = d[i+1];
var b = d[i+2];
// CIE luminance for the RGB
// The human eye is bad at seeing red and blue, so we de-emphasize them.
var v = 0.2126*r + 0.7152*g + 0.0722*b;
d[i] = d[i+1] = d[i+2] = v