HTML5 canvas stroke() thick and fuzzy

28,455

Solution 1

For some reason, your canvas is stretched. Because you have its css property width set to 100%, it is stretching it from some sort of native size. It's the difference between using the css width property and the width attribute on the <canvas> tag. You might want to try using a bit of javascript to make it fill the viewport (see jQuery .width()):

jQuery(document).ready(function(){
    var canvas = document.getElementById('drawing');
    canvas.width(($(window).width()).height($(window).height());
    var context = canvas.getContext('2d');
    //...

Solution 2

The blurry problem will happen if you use css to set the canvas height and width instead of setting height and width in the canvas element.

<style>
  canvas { height: 800px; width: 1200px; }      WRONG WAY -- BLURRY LINES
</style>

<canvas height="800" width="1200"></canvas>     RIGHT WAY -- SHARP LINES

Solution 3

The way I do it is to set the canvas element to a width and height in the css, and then set the canvas.width = canvas.clientWidth and canvas.height = canvas.clientHeight

var canvas =  document.getElementById("myCanvas");
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
var context = canvas.getContext("2d");

Solution 4

You haven't indicated canvas size in pixels, so it is scaled up. It is 300x150 here. Try setting the width, height

Solution 5

On retina displays you also need to scale (in addition to the accepted answer):

var context = canvas.getContext('2d');
context.scale(2,2);
Share:
28,455
Valeria
Author by

Valeria

Updated on July 14, 2022

Comments

  • Valeria
    Valeria almost 2 years

    I'm trying to allow the user to draw a rectangle on the canvas (like a selection box). I'm getting some ridiculous results, but then I noticed that even just trying the code from my reference here, I get huge fuzzy lines and don't know why.

    it's hosted at dylanstestserver.com/drawcss. the javascript is inline so you can check it out. I am using jQuery to simplify getting the mouse coordinates.