How can i improve my Html5 Canvas pathing Quality?

后端 未结 6 1200
庸人自扰
庸人自扰 2020-12-29 23:01

I have been writing a little javascript plugin, and i am having a little trouble with improving the canvas overall quality of the render. I have searched over the web here a

6条回答
  •  一整个雨季
    2020-12-29 23:53

    One reason for blury lines is drawing in-between pixels. This answer gives a good overview of the canvas coordinate system:

    https://stackoverflow.com/a/3657831/4602079

    One way of keeping integer coordinates but still getting crisp lines is to translate the context by 0.5 pixel:

    context.translate(0.5,0.5);
    

    Take a look at the snippet below. The second canvas is translated by (0.5, 0.5) making the line drawn with integer coordinates look crisp.

    That should get your straight lines fixed. Curves, diagonal lines, etc. will be anti-aliased (gray pixels around the strokes). Not much you can do about it. The higher the resolution less visible they are and all lines except for the straight ones look better anti-aliased anyways.

    function draw(ctx){
        ctx.beginPath();
        ctx.moveTo(25, 30);
        ctx.lineTo(75, 30);
        ctx.stroke();
    
        ctx.beginPath();
        ctx.moveTo(25, 50.5);
        ctx.lineTo(75, 50.5);
        ctx.stroke();
    }
    
    draw(document.getElementById("c1").getContext("2d"))
    
    var ctx = document.getElementById("c2").getContext("2d");
    ctx.translate(0.5, 0.5);
    draw(ctx);
        
        

提交回复
热议问题