Robert
Robert

Reputation: 43

HTML 5 Canvas: remove color gradient from line edges

I'm trying to draw a black line on a white-filled canvas. For some reasons, only the inner pixels of that line (lineWidth = 3) are really black. The more I go to the edges of the line, the broghter in steps of the greyscale it gets. If I draw it with lineWith = 1, no pixels are really black.

I wrote a little demonstration of what happens: http://jsfiddle.net/xr5az/

Just for completeness, here is the code again:

<html>

<head>
<script type="text/javascript">
function page_loaded()
{
  var cv = document.getElementById("cv");
  var ctx = cv.getContext("2d");
  ctx.fillStyle = "#ffffff";
  ctx.strokeStyle = "#000000";
  ctx.lineWidth = 3;
  ctx.lineCap = "round";
  ctx.lineJoin = "bevel";
  ctx.fillRect(0, 0, cv.width, cv.height);
  ctx.moveTo(5, 5);
  ctx.lineTo(10, 10);
  ctx.stroke();
  var imgdata = ctx.getImageData(0, 0, cv.width, cv.height);
  for (var y = 0; y < cv.height; y ++)
  {
    for (var x = 0; x < cv.width; x ++)
    {
      var idx = 4 * (y * cv.width + x);
      var c = imgdata.data[idx]<<16 | imgdata.data[idx+1]<<8 | imgdata.data[idx+2];
      if (c != 0xffffff)
      {
        document.getElementById("debug").innerHTML += x+"x, "+y+"y: "+c.toString(16)+"<br/>";
      }
    }
  }
}
</script>
</head>

<body onload="page_loaded()">
<p>
<canvas id="cv" width="15" height="15"></canvas>
</p>
<p>
Found colors:
<div id="debug"></div>
</body>

</html>

Why isn't the line just black and how may I fix this issue?

Thanks a lot!

Upvotes: 4

Views: 1554

Answers (1)

ViliusL
ViliusL

Reputation: 4715

  1. draw vertically or horizontally and add 0.5 (jsfiddle.net/xr5az/2/) - you will get only black and white colours. (note that i hided line begin and end, it would be grey ...)

    ctx.moveTo(-2, 5.5); ctx.lineTo(17, 5.5); ctx.stroke();

  2. when you add angle, system adds extra grey colors pixels, without it, line would look bad.

  3. if you want to get line only from black color, draw many separate pixels (or squares if you want lineWidth > 1) between line start and end points.

p.s. sorry for broken fiddle link, system kicked my message even with code included like 10 times ...

Upvotes: 2

Related Questions