舉國哀傷,如何用一行代碼讓網站變灰?

剛剛 在網上看到一個最簡單的解決辦法,就是:html

-webkit-filter:grayscale(0.94);

給html根節點添加這行代碼就能夠web

html.gray{
    -webkit-filter:grayscale(0.94);
}

兼容性:canvas

html {
    -webkit-filter: grayscale(100%);
    -moz-filter: grayscale(100%);
    -ms-filter: grayscale(100%);
    -o-filter: grayscale(100%);
    filter: grayscale(100%);
    filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
}

若是還有瀏覽器不兼容,那隻能搬出JS了
var imgObj = document.getElementById('imgToGray');    瀏覽器

function gray(imgObj) {  
    var canvas = document.createElement('canvas');  
    var canvasContext = canvas.getContext('2d');   code

    var imgW = imgObj.width;  
    var imgH = imgObj.height;  
    canvas.width = imgW;  
    canvas.height = imgH;   orm

    canvasContext.drawImage(imgObj, 0, 0);  
    var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);   htm

    for (var y = 0; y < imgPixels.height; y++) {  
        for (var x = 0; x < imgPixels.width; x++) {  
            var i = (y * 4) * imgPixels.width + x * 4;  
            var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;  
            imgPixels.data[i] = avg;  
            imgPixels.data[i + 1] = avg;  
            imgPixels.data[i + 2] = avg;  
        }  
    }  
    canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);  
    return canvas.toDataURL();  
}  
imgObj.src = gray(imgObj);get

相關文章
相關標籤/搜索