KineticJS:Bezier曲线随着流动而变宽 - 如何添加圆角?

时间:2013-10-06 18:43:03

标签: canvas kineticjs shapes bezier

我正在使用KineticJS画出一条在流动时变宽的贝塞尔曲线。这是一个例子:

flat http://www.market-research-services.com/starpowermedia/for_distribution/bezier-curve-with-flat-end.png

在广角端给它圆角的一些可能的方法是什么?例如:

rounded http://www.market-research-services.com/starpowermedia/for_distribution/bezier-curve-with-rounded-end.jpg

非常感谢所有人提供任何信息。

供参考,这是我目前正在使用的代码:

//based on: http://stackoverflow.com/questions/8325680/how-to-draw-a-bezier-curve-with-variable-thickness-on-an-html-canvas                
//draw a bezier curve that gets larger as it flows
function plotFlow(centerLeft, centerRight, thicknessLeft, thicknessRight, color, desiredWidth) {
    var bezierLayer = mainLayer.getAttrs().bezierLayer;
    var context = bezierLayer.getContext();
    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};

    var bezierCurve = new Kinetic.Shape({
        drawFunc: function(canvas) {
            var context = canvas.getContext('2d');
            context.fillStyle = this.getFill();
            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();
            canvas.stroke(this);

        },
        fill: color,
        stroke: color,
        strokeWidth: 2
    });

    bezierCurve.setAttrs({'color': color, 'leftUpper': leftUpper, 'leftLower': leftLower, 'rightUpper': rightUpper, 'rightLower': rightLower, 'cp1Upper': cp1Upper, 'cp2Upper': cp2Upper, 'cp1Lower': cp1Lower, 'cp2Lower': cp2Lower});

    bezierLayer.add(bezierCurve);
}

1 个答案:

答案 0 :(得分:1)

  1. 给出rightUpper和rightLower之间的线段(称为UL)。
  2. 找到UL的中点。
  3. 找出UL的斜率。
  4. 从UL的中点垂直延伸线。
  5. 绘制一个context.quadraticCurveTo,从右上角到右下角,垂直线上的控制点(垂直线越远,曲线越尖)。
  6. 或者,你可以画一个bezierCurveTo。只需确保2个控制点与UL线等距,以避免出现倾斜曲线。
  7. 使用二次或Bezier曲线时,请确保控制点与UL非常接近。离得越远,你就越能得到一条完整的曲线,而不是圆角。