html 5画布线宽

时间:2013-07-01 16:23:40

标签: html5 canvas line

当画一条线时,html画布线的哪些方法可以让我改变线宽? 此示例采用所有线段的最后一行宽度。

<!DOCTYPE HTML>
<html>
  <head>
  </head>
  <body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        context.lineTo(100, 0);
        context.beginPath();
        context.lineWidth = .5;
        context.lineTo(200, 20);        
        context.lineWidth = 1;      
        context.lineTo(100, 40);        
        context.lineWidth = 2;
        context.lineTo(200, 60);
        context.lineWidth = 3;
        context.lineTo(100, 80);        
        context.lineWidth = 4;
        context.lineTo(200, 100);
        context.lineWidth = 5;
        context.lineTo(100, 120);
        context.lineWidth = 6;
        context.lineTo(200, 140);       
        context.lineWidth = 7;
        context.lineTo(100, 160);
        context.lineWidth = 8;
        context.lineTo(200, 180);
        context.lineWidth = 10;
        context.lineTo(100, 200);
        context.stroke();
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

打破你的道路。

更改

    context.beginPath();
    context.lineWidth = .5;
    context.lineTo(200, 20);        
    context.lineWidth = 1;      
    context.lineTo(100, 40);
    ...
    context.lineWidth = 10;
    context.lineTo(100, 200);
    context.stroke();

    context.beginPath();
    context.lineWidth = .5;
    context.lineTo(200, 20);       
    context.stroke();
    context.beginPath();
    context.lineWidth = 1;      
    context.lineTo(100, 40);
    context.stroke();
    ...
    context.beginPath();
    context.lineWidth = 10;
    context.lineTo(100, 200);
    context.stroke();

当然,如果你将你的片段放在一个结构中并在它们上面循环,它会更干净。