Progressive line width

I am learning how to use a canvas, and I wanted to create a drawing application. I can easily draw lines and shapes, but I cannot figure out how to change the line width from a given size to each other with the same line.

I would like to do something like:

Draw a line from point (0, 1) to point (10, 10) and size from 10 to 5

Is it possible?

+4
source share
1 answer

try this, the idea is to draw a few lines

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

function drawline(xo,yo,xf,yf,wo,wf, parts){

    var stepX = (xf-xo)/parts;
    var stepY = (yf-yo)/parts;
    var stepW = (wf-wo)/parts;
    for(var i=1; i<=parts; ++i){
      ctx.beginPath();
      ctx.lineWidth = wo + stepW*i;
      ctx.moveTo(xo+stepX*(i-1), yo+stepY*(i-1));
      ctx.lineTo(xo+stepX*i, yo+stepY*i);
      ctx.stroke();
    }
}

drawline(10,10,150,150,1,10, 100);
drawline(10,10,150,300,1,10, 100);
<canvas id="canvas1" width="500" height="500">
</canvas>
Run code

or, better, a solution using the trapezoid (the general solution is not shown)

explanation

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

function drawline(xo,yo,xf,yf,wo,wf){
    //if xf == xo vertical line, failure ;)
    var m = (yf-yo)/(xf-xo);
    //if m==0, horizontal line, failure
    var mp = -1 / m;
    var angle = Math.atan(mp);
    var dy1 = Math.sin(angle) * wo/2;
    var dx1 = Math.cos(angle) * wo/2;
    var dy2 = Math.sin(angle) * wf/2;
    var dx2 = Math.cos(angle) * wf/2;

    //depending on the positions of xo,yo,xf and yf change signs
    //this isn't a general solution
    //solution for xo<xf and yo<yf
    var x1 = xo + dx1;
    var y1 = yo + dy1;
    var x2 = xo - dx1;
    var y2 = yo - dy1;
    var x3 = xf - dx2;
    var y3 = yf - dy2;
    var x4 = xf + dx2;
    var y4 = yf + dy2;

    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.lineTo(x3, y3);
    ctx.lineTo(x4, y4);
    ctx.fill();
}

drawline(10,10,150,150,1,10);
drawline(10,10,150,300,1,10);
<canvas id="canvas1" width="500" height="500">
</canvas>
Run code
+3
source

Source: https://habr.com/ru/post/1589213/


All Articles