调整画布大小时图像上的滤镜丢失

时间:2019-03-03 03:17:50

标签: javascript canvas

我一直在尝试在画布上加载的图像上放置滤镜(例如亮度,对比度)。 以下是我在做什么的摘要

/******Loading Image in Canvas******/
        let canvas = document.getElementById('demo');
        let ctx = canvas.getContext('2d');
        var reader = new FileReader();
        reader.onload = function(event){
            var img = new Image();
            img.onload = function(){
                canvas.width = 220;
                canvas.height = 250;
                ctx.drawImage(img,0,0,canvas.width,canvas.height);
            }
            img.src = event.target.result;
            self.oldImg = event.target.result;
        }
        reader.readAsDataURL(xevents.target.files[0]);  

我添加了亮度,对比度逻辑,并且在图像上工作正常。 当我对图像进行任何操作(例如调整画布大小(使用可调整大小的jquery UI))时,实际上就会出现问题。应用的过滤器会丢失。 以下是调整大小后在画布上重新绘制的代码段。

    $(".stretch").resizable({ resize: function(event, ui) {
        $("#demo", this).each(function() { 
            $(this).attr({ width: ui.size.width, height: ui.size.height });
            self.reDraw(this);
        });
    } });

reDraw () {
    var img = new Image();
    var canvas = document.getElementById('demo');
    var c = canvas.getContext("2d");
    img.src = this.oldImg;
    c.drawImage(img, 0, 0, canvas.width, canvas.height);
}

我相信,由于它再次创建了一个新的图像对象(new Image()),因此过滤器已经丢失。 谁可以帮我这个事。我希望在调整画布大小时保留过滤器。

感激!谢谢

更新

process (type, amount) {
    var img = new Image();
    var canvas = document.getElementById('demo');
    var c = canvas.getContext("2d");
    img.src = this.oldImg;
    c.drawImage(img, 0, 0, canvas.width, canvas.height);
    let imgData = c.getImageData(0, 0, canvas.width, canvas.height);
    let data = imgData.data;
    if(type === 'b') {
        for (let i = 0; i < data.length; i += 4) {
            data[i] += amount;
            data[i + 1] += amount;
            data[i + 2] += amount;
        }
    }
    if(type === 'c') {
        amount = (amount/100) + 1;  //convert to decimal & shift range: [0..2]
        let intercept = 128 * (1 - amount);
        for(let i=0;i<data.length;i+=4){   //r,g,b,a
            data[i] = data[i]*amount + intercept;
            data[i+1] = data[i+1]*amount + intercept;
            data[i+2] = data[i+2]*amount + intercept;
        }
    }
    c.putImageData(imgData, 0, 0);
}

0 个答案:

没有答案