0

我发现了几个小书签可以反转页面上的所有颜色或仅反转文本,但不是反转图像。我该怎么做呢?Javascript 不是我的专长。

4

1 回答 1

1

您必须获取数组中的图像,并用画布替换这些图像。

未经测试的代码(注意:由于安全限制,图像源必须在同一域中):

function replaceImageByCanvas(image) {
    var canvas = document.createElement('canvas');
    image.after(canvas);
    var context = canvas.getContext('2d');
    canvas.width = image.width();
    canvas.height = image.height();

    var image_obj = new Image(); 
        var newImage = context.createImageData(canvas.width, canvas.height);
        var arr = context.getImageData(0, 0, canvas.width, canvas.height);
        var pixels = arr.data;

        for(var i = 0; i < pixels.length; i+=4){
            var r = 255 - pixels[i];
            var g = 255 - pixels[i + 1];
            var b = 255 - pixels[i + 2];
            var a = pixels[i + 3];
            newImage.data[i] = r;
            newImage.data[i + 1] = g;
            newImage.data[i + 2] = b;
            newImage.data[i + 3] = a;
        }

        context.clearRect(0, 0, canvas.width, canvas.height);
        context.putImageData(newImage, 0, 0);
    image_obj.src = image.attr('src');
    image.remove();
};

$('img').each(function(index, element) {
  $(this).one('load', function() {
    replaceImageByCanvas($(element));|
  });
});
于 2013-09-30T14:00:41.200 回答