Skip to content
Advertisement

JavaScript – Get brightness of single character

I am making an image/video to ASCII converter. For this, I need to get the average darkness for each character I will use. I modified the answer to this question, which gets the average brightness of an image. But it keeps saying that the brightness is 0. What did I do wrong?

JavaScript
JavaScript
JavaScript

Advertisement

Answer

For starters, please don’t set CSS properties on canvas nodes — this stretches and warps the image. Only use the HTML element attributes canvas.width and canvas.height to get and set the width and height of the canvas.

As for the main issue, all of your rgb values are 0 (black) on your canvas by default. If you print data[x+3] you’ll see the alpha channel varies from 0-255 but this is never taken into consideration.

Depending on what you’d like to do, simply average the alpha in this channel, or fill the canvas with white (a non-transparent background color) before drawing your text and then use rgb as you’re doing.

JavaScript
JavaScript
JavaScript

You can try this with ctx.fillRect(0, 0, canvas.width / 2, canvas.height); instead of the character and you’ll get 127 as the average, which is expected because you’ve filled half the canvas with black.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement