1

I made this plnkr to demonstrate my problem. I don't understand why the line as drawn looks 'thicker' or 'fatter' when its drawn at an angle rather than straight across page.

How can I draw this shape with consistent line width?

html:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <canvas id="canvas"></canvas>
  </body>
  <script src="script.js"></script>
</html>

css:

#canvas {
  width: 100%;
  height: 80px;
  border: 1px solid black;
}

js (note that the line width is just set once to '5' before drawing begins).:

(function () {
    var canvas = document.getElementById('canvas');
    if (!canvas.getContext) {
        // browser does not support HTML canvas
        return;
    }
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "#000000";
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.lineTo(0, canvas.height - 10);
    var twoThirds= (canvas.width / 3) * 2;
    var oneSixth= (canvas.width / 6);
    ctx.lineTo(twoThirds, canvas.height - 10);
    ctx.lineTo(twoThirds + oneSixth, 5);
    ctx.lineTo(canvas.width-3, canvas.height - 10);
    ctx.stroke();
})();
Dan Schnau
  • 1,505
  • 14
  • 17
  • **"Don't resize your canvas with CSS"** *at least until you understand how to make it work correctly* – Kaiido Jan 10 '17 at 14:51
  • Possible duplicate of [Canvas is stretched when using CSS but normal with "width" / "height" properties](http://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-but-normal-with-width-height-properties) – Kaiido Jan 10 '17 at 14:52
  • I'm not resizing the canvas though? Just to be sure, I verified the issue still happens when the canvas width is a fixed pixel width instead of `100%`. – Dan Schnau Jan 10 '17 at 15:48
  • 1
    Just remove your css you'll the real size of your canvas, and of your line – Kaiido Jan 10 '17 at 16:27
  • Oh! Thank you. That points me to a better understanding. (If you want to add your comment to an answer I'll gladly mark it right). – Dan Schnau Jan 10 '17 at 18:29

1 Answers1

2

Your canvas does not have square "Pixels" due to how you've sized it.

you can't see this for the flat line, but the diagonal lines show it.

The HTML canvas element has the properties width and height which you need to set.

Here is your modified code.

new version

#canvas {
  width: 300px;
  height: 300px;
  border: 1px solid black;
}
    <canvas id="canvas" width="300" height="300"></canvas>

If you want a responsive canvas, you will need to update the width and height properties whenever it changes size.

speciesUnknown
  • 1,644
  • 2
  • 14
  • 27