Transparency effect in Canvas

How to apply a opacity filter by modifying the alpha channel.

Demonstration

Canvas This demo requires a modern browser.

Opacity level (0=transparent, 255=opaque)

Source code

function dispImage() 
{
  var level = document.getElementById("level").value;
  var canvas = document.getElementById("canvas1");
  var context = canvas.getContext("2d");
  var image = new Image();
  image.src = "https://www.scriptol.com/design/images/infinite-oz.jpg";

  context.drawImage(image, 0, 0, 562, 350);    
  var ipic = context.getImageData(0, 0, 562, 350);
  var idata = ipic.data;
  for (var i = 0; i < idata.length; i += 4) 
  {
    idata[i+3] = level;
  }
  context.putImageData(ipic, 0, 0);
}

Explanations...

An image is loaded into memory when the src attribute of a newly created image object is assigned.
The drawImage method displays the image on the canvas.

The getImageData method creates an array of RGBA color components (red, green, blue, alpha = opacity) of each pixel from this image.

The alpha channel is modified for each pixel. This is the fourth byte of each pixel in the array.

The putImageData method put in the canvas the image modified through the array.