如何在HTML画布上绘制具有可变厚度的贝塞尔曲线?

时间:2011-11-30 12:04:43

标签: javascript html5-canvas bezier

我想用连接框的贝塞尔曲线进行可视化。更重要的边缘应该更厚。每个盒子都有一个输出,但输入很多。因此,我希望保持凹面边缘的厚度不变(以节省空间)并仅改变外边缘的厚度(每个盒子只有一个)。

这就是为什么我想在每一端绘制不同厚度的bezier疗法。它们应在HTML canvas元素上呈现。我知道context.bezierCurveTo(),但只允许曲线的一个厚度。

有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:3)

假设您正在绘制一条曲线,在x1,y1处厚2倍r,而控制点1在x-driection中,那么您可以执行以下操作:

  canvas.fillStyle = "red";  

  canvas.beginPath();  
  canvas.moveTo(x1, y1-r);  
  canvas.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  canvas.bezierCurveTo(cpx2, cpy2, cpx1, cpy1, x1, y1+r);
  canvas.lineTo(x1, y1+r);  
  canvas.fill(); 

答案 1 :(得分:2)

如果其他人想要做类似的事情,这是我的代码:

function plotFlow(context, centerLeft, centerRight, thicknessLeft, thicknessRight) {
    var leftUpper = {x: centerLeft.x, y: centerLeft.y - thicknessLeft / 2};
    var leftLower = {x: centerLeft.x, y: leftUpper.y + thicknessLeft};
    var rightUpper = {x: centerRight.x, y: centerRight.y - thicknessRight / 2};
    var rightLower = {x: centerRight.x, y: rightUpper.y + thicknessRight};

    var center = (centerRight.x + centerLeft.x) / 2;
    var cp1Upper = {x: center, y: leftUpper.y};
    var cp2Upper = {x: center, y: rightUpper.y};
    var cp1Lower = {x: center, y: rightLower.y};
    var cp2Lower = {x: center, y: leftLower.y};

    context.beginPath();
    context.moveTo(leftUpper.x, leftUpper.y);
    context.bezierCurveTo(cp1Upper.x,cp1Upper.y, cp2Upper.x,cp2Upper.y, rightUpper.x,rightUpper.y);
    context.lineTo(rightLower.x, rightLower.y);
    context.bezierCurveTo(cp1Lower.x,cp1Lower.y, cp2Lower.x,cp2Lower.y, leftLower.x,leftLower.y);
    context.lineTo(leftUpper.x, leftUpper.y);
    context.fill();

    if (typeof context.endPath == 'function') {
        context.endPath();
    }
}