改变图片的颜色

    1. aPix = oImgData.data;
    2. for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
    3. aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
    4. }
    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <title>Document</title>
    7. </head>
    8. <body>
    9. <canvas id="bricks" width="100px" height="100px"></canvas>
    10. <script>
    11. const canvas = document.getElementById('bricks')
    12. var dataURL = canvas.toDataURL()
    13. console.log('dataURL', dataURL)
    14. </script>
    15. <hr />
    16. <img class="grayscale" crossorigin=''
    17. src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3413156137,1378410039&fm=26&gp=0.jpg"
    18. alt="Description of my picture" />
    19. <script>
    20. window.addEventListener("load", removeColors);
    21. function showColorImg() {
    22. this.style.display = "none";
    23. this.nextSibling.style.display = "inline";
    24. }
    25. function showGrayImg() {
    26. this.previousSibling.style.display = "inline";
    27. this.style.display = "none";
    28. }
    29. function removeColors() {
    30. var aImages = document.getElementsByClassName("grayscale"),
    31. nImgsLen = aImages.length,
    32. oCanvas = document.createElement("canvas"),
    33. oCtx = oCanvas.getContext("2d");
    34. for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
    35. oColorImg = aImages[nImgId];
    36. nWidth = oColorImg.offsetWidth;
    37. nHeight = oColorImg.offsetHeight;
    38. oCanvas.width = nWidth;
    39. oCanvas.height = nHeight;
    40. oCtx.drawImage(oColorImg, 0, 0);
    41. oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
    42. aPix = oImgData.data;
    43. nPixLen = aPix.length;
    44. for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
    45. aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
    46. }
    47. oCtx.putImageData(oImgData, 0, 0);
    48. oGrayImg = new Image();
    49. oGrayImg.src = oCanvas.toDataURL();
    50. oGrayImg.onmouseover = showColorImg;
    51. oColorImg.onmouseout = showGrayImg;
    52. oCtx.clearRect(0, 0, nWidth, nHeight);
    53. oColorImg.style.display = "none";
    54. oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
    55. }
    56. }
    57. </script>
    58. </body>
    59. </html>