HTML5 canvas stroke() thick and fuzzy

后端 未结 7 1734
野性不改
野性不改 2020-12-09 08:04

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 co

相关标签:
7条回答
  • 2020-12-09 08:29

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

    var context = canvas.getContext('2d');
    context.scale(2,2);
    
    0 讨论(0)
  • 2020-12-09 08:31

    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.

    0 讨论(0)
  • 2020-12-09 08:34

    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.

    0 讨论(0)
  • 2020-12-09 08:43

    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');
        //...
    
    0 讨论(0)
  • 2020-12-09 08:43

    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");
    
    0 讨论(0)
  • 2020-12-09 08:45

    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
    
    0 讨论(0)
提交回复
热议问题