HTML5 canvas stroke() thick and fuzzy

独自空忆成欢 提交于 2019-11-30 07:58:23

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');
    //...

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

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");

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

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

var context = canvas.getContext('2d');
context.scale(2,2);

The css sizing issue mentioned in these comments is correct, but another more subtle thing that can cause blurred lines is forgetting to call make a call to context.beginPath() before drawing a line. Without calling this, you will still get a line, but it won't be smoothed which makes the line looks like a series of steps.

I found the reason mine was blurry was that there was a slight discrepancy between the inline width and the CSS width.

I have both inline width/height parameters AND css width/height assigned to my canvas, because I need to keep its physical dimensions static, while increasing its inline dimensions for retina screens.

Check yours are the same if you have a situation like mine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!