Drawing lines with canvas by using for loop

前端 未结 2 1741
谎友^
谎友^ 2021-01-12 18:52

I am trying to draw lines with canvas and I am changing the coordinates with a for loop.

here is my canvas element:



        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 19:07

    That's again the eternal issue of forgetting to call beginPath.
    Each time you call moveTo then lineTo, you create a new *sub*path, which adds to the current Path.
    Then each time you call stroke(), the current path, so all the current subpaths get re-drawn, when the last added path is drawn for the first time.
    Since opacities will add-up, top lines will reach 100% opacity (alpha=255) when the bottom line, drawn once, will have a 20% opacity (lineWidth=0.2) .

    In your second fiddle, you stroke only once, so all lines have 20% opacity, which is correct for the 0.2 lineWidth.

    So : use beginPath before drawing a new figure.
    In this case you have two choices :
    • draw line by line OR
    • draw once a path with all lines as subpath.

    (see code below).

    TIP : To get clean lines remember that pixels's center is at the (+0.5, +0.5) coordinates of each pixels, so a 'trick' is to translate by 0.5, 0.5 on app start, then only use rounded coordinates and lineWidth.

    1) draw line by line

    http://jsfiddle.net/gamealchemist/J6zzD/6/

    var c = document.getElementById('c');
    var ctx = c.getContext('2d');
    ctx.translate(0.5, 0.5);
    ctx.lineWidth = 1;
    
    for (var y = 18; y < 300; y += 18) {
        strokeLine(ctx, y);
    }
    
    function strokeLine(ctx, y) {
        ctx.beginPath();
        ctx.strokeStyle = 'red';
        ctx.moveTo(0, y);
        ctx.lineTo(300, y);
        ctx.stroke();
    }
    

    2) draw multiple subPath : (you can have only one color for one stroke() )

    http://jsfiddle.net/gamealchemist/J6zzD/7/

    var c = document.getElementById('c');
    var ctx = c.getContext('2d');
    ctx.translate(0.5, 0.5);
    ctx.lineWidth = 1;
    
    ctx.strokeStyle = 'red';
    
    ctx.beginPath();
    for (var y = 18; y < 300; y += 18) {
        addLineSubPath(ctx, y);
    }
    ctx.stroke();
    
    function addLineSubPath(ctx, y) {
        ctx.moveTo(0, y);
        ctx.lineTo(300, y);
    }
    

提交回复
热议问题