javascript - 渐进线宽

标签 javascript canvas

我正在学习如何使用 Canvas ,我想制作一个绘画应用程序。我可以很容易地画出线条和形状,但我不明白如何用同一条线将一条线的宽度从指定大小更改为另一个。

我想做这样的事情:

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

这可能吗?

最佳答案

试试这个,思路是画几条线

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>

关于javascript - 渐进线宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374767/

相关文章:

Javafx Canvas 未正确清除。

javascript - 使用按位运算符(JSFeat)修改图像像素

javascript - 无法使用 require.js 加载 jquery

javascript - 如何转义 CSS 标识符开头的数字?

javascript - 嵌套的 try、catch 和 async、await 请求

javascript - 在 javascript 中使用文件名和计划函数调用

javascript - 使用高阶组件为每个组件添加事件监听器

javascript - 单击时的 Html5 Canvas 图像

c# - excanvas js 在 IE8 中不工作

javascript - Canvas 不显示