Canvas drawings, like lines, are blurry

前端 未结 10 977
野的像风
野的像风 2020-11-27 15:15

I have a

and canvas, which is drawn using:

context.lineWidth = 1;
context.strokeStyle = \"gray\         


        
10条回答
  •  伪装坚强ぢ
    2020-11-27 15:52

    Ok, I've figured this out once and for all. You need to do two things:

    1. place any lines on 0.5 px. Refer to this, which provides a great explanation:

    https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors#A_lineWidth_example

    1. There are essentially two heights and two widths associated with the canvas. There is the canvas height and width and then there is the css style height and width of the element. These need to be in sync.

    To do this, you need to calculate the css height and width as:

     var myCanvasEl = document.getElementById('myCanvas');
     var ctx = myCanvasEl.getContext('2d');
     myCanvasEl.style.height = myCanvasEl.height / window.devicePixelRatio + "px";
     myCanvasEl.style.width = myCanvasEl.width / window.devicePixelRatio + "px";
     
    

    where myCanvasEl.style.height and myCanvasEl.style.widthis the css styling height and width of the element, while myCanvasEl.height and myCanvasEl.width is the height and width of the canvas.

    OLD ANSWER (superseded by above):

    This is the best solution I've found in 2020. Notice I've multiplied the devicePixelRatio by 2:

     var size = 100;
     var scale = window.devicePixelRatio*2;
     context.width = size * scale;
     cartesian_001El.style.height = cartesian_001El.height / window.devicePixelRatio + "px";
     cartesian_001El.style.height = cartesian_001El.height / window.devicePixelRatio + "px";
     context.height = size * scale;
     context.scale(scale, scale);
    

提交回复
热议问题