渐进线宽

时间:2015-05-21 13:10:49

标签: javascript canvas

我正在学习如何使用画布,我想制作一个绘画应用程序。我可以轻松地绘制线条和形状,但我无法理解如何使用相同的线条将线条的宽度从指定的大小更改为另一条线。

我想做点什么:

从点(0,1)到点(10,10)画一条线,大小从10到5

有可能吗?

1 个答案:

答案 0 :(得分:3)

试试这个,想法是绘制几行

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>

或更好的解决方案,使用梯形(没有一般解决方案显示)

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>