<1> Canvas.
1,灰度图:
js:
function showAsGray() { var imgNode = document.getElementById(‘img‘); if(!imgNode)return false; var origSource = imgNode.src; imgNode.onmouseover = function () { imgNode.src = createGray(imgNode); }; imgNode.onmouseout = function () { imgNode.src = origSource; } } function createGray(img) { var canvas = document.createElement(‘canvas‘); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext(‘2d‘); ctx.drawImage(img,0,0); var raw = ctx.getImageData(0,0,img.width,img.height); for(var i=0;i<raw.height;i++){ for(var j=0;j<raw.width;j++){ var x = i*4 * raw.width + j*4; var r = raw.data[x]; var g = raw.data[x+1]; var b = raw.data[x+2]; //var a = raw.data[x+3]; var a = 1; raw.data[x] = raw.data[x+1] = raw.data[x+2] = a* ((r+g+b)/3); } } ctx.putImageData(raw,0,0,0,0,raw.width,raw.height); return canvas.toDataURL(); } window.onload = showAsGray;
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <img src="images/img.jpg" id="img"> <script src="image_gray.js"></script> </body> </html>
.