【问题标题】:jQuery - BW effect using the HTML5 canvasjQuery - 使用 HTML5 画布的 BW 效果
【发布时间】:2011-05-01 19:07:07
【问题描述】:

如何让正常图像在鼠标悬停时变为黑白,鼠标移开时恢复正常?

【问题讨论】:

  • 您想手动完成还是想要一个可以做到这一点的库?

标签: javascript jquery html canvas


【解决方案1】:

来自http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html

(我自己的评论)

// create canvas element
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
// assuming imgObj is a DOM representation of your image, get the width    
var imgW = imgObj.width;
// ... and the height
var imgH = imgObj.height;
// set the canvas to the image dimensions
canvas.width = imgW;
canvas.height = imgH;
// draw the image on the canvas
canvasContext.drawImage(imgObj, 0, 0);
// get every pixel in the image
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
// cycle through the pixels vertically
for(>var y = 0; y < imgPixels.height; y++){
     // cycle through the pixels horizontally
     for(>var x = 0; x < imgPixels.width; x++){
          var i = (y * 4) * imgPixels.width + x * 4;
          // create an average grayscale color for the pixel
          var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
          // set the pixel to the newly created average color
          imgPixels.data[i] = avg;
          // do the same for the next two pixels
          imgPixels.data[i + 1] = avg;
          imgPixels.data[i + 2] = avg;
     }
}
// overwrite the canvas image with the newly created array of pixels
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
// get a data URL which is to be used in the SRC attribute of the image
return canvas.toDataURL();

此外,如果您想要一个“即插即用”jQuery 插件 为您执行此操作,请查看this jQuery plugin that desaturates the image for you

【讨论】:

  • 嵌套的fors也有点丑,如果你使用imgPixels.length可以搭配一个
【解决方案2】:

这是我看到的函数:

    $(document).ready(function(){
        $("img.a").hover(
            function() {
                $(this).stop().animate({"opacity": "0"}, "slow");
            },
            function() {
                $(this).stop().animate({"opacity": "1"}, "slow");
            });

     });

这里是css:

div.fadehover {
    position: relative;
    }

img.a {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 10;
    }

 img.b {
    position: absolute;
    left: 0;
    top: 0;
    }

我从这里得到这个:http://bavotasan.com/tutorials/creating-a-jquery-mouseover-fade-effect/

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 2012-11-23
    相关资源
    最近更新 更多