Pixel by pixel Bézier Curve

后端 未结 4 1377
萌比男神i
萌比男神i 2020-12-14 04:15

The quadratic/cubic bézier curve code I find via google mostly works by subdividing the line into a series of points and connects them with straight lines. The rasterization

4条回答
  •  庸人自扰
    2020-12-14 04:36

    You can use De Casteljau's algorithm to subdivide a curve into enough pieces that each subsection is a pixel.

    This is the equation for finding the [x,y] point on a Quadratic Curve at interval T:

    // Given 3 control points defining the Quadratic curve 
    // and given T which is an interval between 0.00 and 1.00 along the curve.
    // Note:
    //   At the curve's starting control point T==0.00.
    //   At the curve's ending control point T==1.00.
    
    var x = Math.pow(1-T,2)*startPt.x + 2 * (1-T) * T * controlPt.x + Math.pow(T,2) * endPt.x; 
    var y = Math.pow(1-T,2)*startPt.y + 2 * (1-T) * T * controlPt.y + Math.pow(T,2) * endPt.y; 
    

    To make practical use of this equation, you can input about 1000 T values between 0.00 and 1.00. This results in a set of 1000 points guaranteed to be along the Quadratic Curve.

    Calculating 1000 points along the curve is probably over-sampling (some calculated points will be at the same pixel coordinate) so you will want to de-duplicate the 1000 points until the set represents unique pixel coordinates along the curve.

    There is a similar equation for Cubic Bezier curves.

    Here's example code that plots a Quadratic Curve as a set of calculated pixels:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    var points=[];
    var lastX=-100;
    var lastY=-100;
    var startPt={x:50,y:200};
    var controlPt={x:150,y:25};
    var endPt={x:250,y:100};
    
    for(var t=0;t<1000;t++){
      var xyAtT=getQuadraticBezierXYatT(startPt,controlPt,endPt,t/1000);
      var x=parseInt(xyAtT.x);
      var y=parseInt(xyAtT.y);
      if(!(x==lastX && y==lastY)){
        points.push(xyAtT);
        lastX=x;
        lastY=y;
      }
    }
    
    $('#curve').text('Quadratic Curve made up of '+points.length+' individual points');
    
    ctx.fillStyle='red';
    for(var i=0;i
    body{ background-color: ivory; }
    #canvas{border:1px solid red; margin:0 auto; }
    
    

    Q

提交回复
热议问题