get canvas pixels after fillText returns 0 Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of get canvas pixels after fillText returns 0 without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I was trying to get the pixel density of any character using HTML5 canvas with JavaScript, but context getImageData returns always an array which seems to be a pitch black rectangle (RGB = [0,0,0] always).

Can anyone tell me what I am doing wrong?

var dcanvas = document.getElementById('char-canvas'),
  dcontext = dcanvas.getContext('2d');

function fontDensity(c) {
  dcanvas.height = 30;
  dcanvas.width = 30;
  dcontext.clearRect(0, 0, dcanvas.width, dcanvas.height);
  dcontext.font = "15px monospace";
  dcontext.fillStyle = "black";
  dcontext.textAlign = "center";
  dcontext.textBaseline = "middle";
  dcontext.fillText(c, dcanvas.width / 2, dcanvas.height / 2);
  var imgd = dcontext.getImageData(0, 0, dcanvas.width, dcanvas.height),
    pix = imgd.data,
    density = 0;
  // Read canvas pixels RGBA!
  for (var i = 0, n = pix.length; i < n; i += 4) {
    density += (pix[i] + pix[i + 1] + pix[i + 2]) / 3;
  }
  //density /= pix.length;
  return density;
}

console.log(fontDensity("a"));
canvas {
  border: 1px solid #000;
  display: block;
  margin: 20px auto;
}
<canvas id="char-canvas" width="30" height="30"></canvas>

Answer

The default pixel value is black transparent so you will always have RGB returning 0 when the color is black.

To distinguish you need to use the alpha channel:

var density = (pix[i] + pix[i + 1] + pix[i + 2]) * (pix[i + 3] / 255) / 3;
//                                               ^^^^^^^^^^^^^^^^^^^^

This is just one way to do it of course. To avoid anti-aliased pixels to be part of the calculation you just use a threshold instead.

We are here to answer your question about get canvas pixels after fillText returns 0 - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji