DEV Community

Abhijeet Singh
Abhijeet Singh

Posted on

Calculating Transparency of an HTML5 Canvas

Alright let's get back to basics here. HTML5 Canvas is a very versatile element capable of both 2d and 3d graphics. It is used in majority of the eye-candy websites featured on websites like awwwards.com and siteinspire.com.

While building one of my older portfolio websites, I built a drawable background that auto-fills once half the Canvas has been drawn on. In order to make this work, I had to calculate the transparency percentage of the Canvas.

You wouldn't believe how simple this can be.

For this article, we'll need to:

  1. Create A Canvas
  2. Draw A Shape
  3. Calculate Transparency

Alright onto Step 1. Let's create a basic HTML Canvas.

<canvas height="500" width="500"/>
Enter fullscreen mode Exit fullscreen mode

We're already at Step 2?

// get the context
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");

// add a shape
context.fillStyle = "#000000";
context.fillRect(0, 0, canvas.height/2, canvas.width/2);
Enter fullscreen mode Exit fullscreen mode

Step 3. Finally we get to write some logic.

// retrieving image data
const imageData = context.getImageData(0, 0, canvas.width, canvas.height).data;
Enter fullscreen mode Exit fullscreen mode

Let's check the imageData values.

console.log('imageData', imageData);

// we get the following array of 1000000 values
// [0, 0, 0, 255, 0, 0, 0, 255............, 1, 1, 1, 255, 1, 1, 1, 255]
Enter fullscreen mode Exit fullscreen mode

As you might have guessed, these are rgba values of each pixel in the canvas, defining the Red, Green, Blue, and Alpha (transparency) values respectively. Each value ranges from 0 to 255.

What we have to focus on here, is the Alpha values. So let's isolate them.

// removing every non-4th value (rgb values)
let alphaValues = imageData.filter((value, index) => index % 4 === (4 - 1));
Enter fullscreen mode Exit fullscreen mode

The method to calculate transparency is pretty simple, we just need the transparent pixels and the total pixel count.

// reworking the filter to remove non-zero alpha values as well
let alphaValues = imageData.filter((value, index) => index % 4 === (4 - 1) && value === 0);

// get the maximum pixel count
const maxPixels = canvas.width * canvas.height;
Enter fullscreen mode Exit fullscreen mode

Now for the finale, let's calculate the transparency ratio and convert it to a percentage.

// tada!
const percentage = (alphaValues.length / maxPixels) * 100;

// a good old fashioned console.log()
console.log(`${percentage}%`);
// "75%"
Enter fullscreen mode Exit fullscreen mode

That's all folks, told ya it was simple.

Top comments (0)