JavaScript use canvas for grayscale Mit JavaScript farbige Bilder in Graustufen umwandeln, durch setzen von class="grayscale" im img-Tag. On using this JavaScripts all images with class "grayscale" get converted to grayscaled images. Example: zoom zoom JavaScript: grayscale.js JavaScript (1,26 kByte) 09.01.2022 00:02 // coding: utf-8 /** Created by: Udo Schmal | https://www.gocher.me/ */ (function () { 'use strict'; function grayscaleImage (img) { var canvas = document.createElement("canvas"); var canvascontext = canvas.getContext("2d"); var imgw = img.naturalWidth; var imgh = img.naturalHeight; canvas.width = imgw; canvas.height = imgh; canvascontext.drawImage(img, 0, 0); var imgpixels = canvascontext.getImageData(0, 0, imgw, imgh); 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); img.src = canvas.toDataURL(); } var els = document.querySelectorAll('img.grayscale'); for (var i=0; i<els.length; i++) { if (!els[i].complete || (els[i].naturalWidth === 0)) { els[i].addEventListener("load", function (e) { grayscaleImage(this); }, false); } else { grayscaleImage(els[i]); } } })(); HTML: grayscale.htm HTML (369 Bytes) 09.01.2022 00:02 <!DOCTYPE html > <html> <head> <meta charset="UTF-8" /> <title>Convert Image to Grayscale</title> </head> <body><img class="grayscale" src="/media/2007/Sammy/DSC02303~300x225.JPG" width="300" height="225" /><img class="grayscale" src="/media/2007/Sammy/DSC02833~300x225.JPG" width="300" height="225" /> <script src="grayscale.js"></script> </body> </html> Author: Udo Schmal, published: 15.08.2014, last modified: 06.09.2023