How to draw a bezier curve with variable thickness on an HTML canvas?

十年热恋 提交于 2019-12-11 03:35:02

问题


I want to make a visualization with bezier curves connecting boxes. More important edges should be thicker. Every box has one output but many inputs. Therefore, I want to keep the thickness of the incomit edges constant (to save space) and alter only the thickness of the outgoing edges (of which there is only one per box).

This is why I want to draw bezier cureves with different thickness at each end. They shall be rendered on an HTML canvas element. I know context.bezierCurveTo() but that only allows one thickness of the curve.

Can anybody help me out?


回答1:


suppose that you are drawing a curve, that is thick 2 times r at x1,y1 and controll-point 1 is in x-driection then you can do something like:

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



回答2:


In case anybody else wants to do something similar, here's my code:

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


来源:https://stackoverflow.com/questions/8325680/how-to-draw-a-bezier-curve-with-variable-thickness-on-an-html-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!