Abe
Abe

Reputation: 298

html 5 canvas linewidth

What methods of html canvas line would permit me to change the linewidth as I draw a line? This example takes the last line width for all line segments.

<!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>

Upvotes: 0

Views: 2101

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382514

Break your path.

Change

    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();

to

    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();

Of course it will be cleaner if you put your segments in a structure and loop over them.

Upvotes: 2

Related Questions