The getImageData() method returns an ImageData object, which copies the pixel data of the specified rectangle of the canvas.
Note: The ImageData object is not an image. It specifies a portion (rectangle) of the canvas and saves the information of each pixel within the rectangle.
For each pixel in the ImageData object, there are four aspects of information, namely the RGBA value:
A - alpha channel (0-255; 0 is transparent, 255 is fully visible)
The color/alpha information exists in the form of an array and is stored in the data attribute of the ImageData object.
Tip: After operating on the color/alpha information in the array, you can use the putImageData() method to copy the image data back to the canvas.
Two codes<!DOCTYPE html><html><head> <meta name=author content=Yeeku.H.Lee(CrazyIt.org) /> <meta http-equiv=Content-Type content=text/html; charset=GBK /> <title> Change transparency</title></head><body><h2> Change transparency</h2><canvas id=mc width=600 height=460 style=border:1px solid black></canvas><script type=text/javascript> // Get the DOM object corresponding to the canvas element var canvas = document.getElementById('mc'); // Get the CanvasRenderingContext2D object for drawing on canvas var ctx = canvas. getContext('2d'); var image = new Image(); image.src = test.png; image.onload = function() { // Use the method with transparency parameters to draw the image drawImage(image, 124, 20, 0.4); } var drawImage = function(image, x, y, alpha) { // Draw the image ctx.drawImage(image, x, y); / / Get the image data starting from x, y, with a width of image.width and a height of image.height // That is, get the drawn image data var imgData = ctx.getImageData(x, y, image.width, image.height); for (var i = 0, len = imgData.data.length; i < len; i += 4) { // Change each pixel Transparency imgData.data[i + 3] = imgData.data[i + 3] * alpha; } // Put back the obtained image data. ctx.putImageData(imgData, x, y); }</script></body></html>Three running results
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.