Search code examples
javascriptbeziervector-graphicsp5.js

Bezier and rotating


Once I call the right function, then the shape of bezier is changing with every step (the curve is becoming larger). These lines of code cause it: direction.mult(length); direction.rotate(angle); I attached a photo to present the problem more clear. The problem has appeared once I multiplied and rotated the vector. This is a sketch with a code- > https://editor.p5js.org/[email protected]/sketches/Syc1qQmnQ

Any ideas how can I fix this?

enter image description here


Solution

  • At the begin the anchor points of the bezier() curve are arranged vertical. The control points are calculated in relation to this arrangement (this.end.x+15, this.end.y/0.9, this.end.x-15, this.end.y/0.9):

    display() {
         stroke(this.color);
         strokeWeight(this.strokeW);
         noFill();
         bezier(this.begin.x, this.begin.y, this.end.x+15, this.end.y/0.9, this.end.x-15, this.end.y/0.9, this.end.x, this.end.y);
    }
    

    But when the vector from the first anchor point to the second anchor point is rotated and scaled, then this calculation doesn't work any more as you expected. You have to calculate the anchor points in relation to the control points:

    class Branch {
    
        ....
    
        display() {
            stroke(this.color);
            strokeWeight(this.strokeW);
            noFill();
            let dir_x = this.end.x - this.begin.x;
            let dir_y = this.end.y - this.begin.y;
            let c1_x  = this.begin.x + dir_x / 3 - dir_y / 6;
            let c1_y  = this.begin.y + dir_y / 3 + dir_x / 6;
            let c2_x  = this.begin.x + dir_x * 2/3 + dir_y / 6;
            let c2_y  = this.begin.y + dir_y * 2/3 - dir_x / 6;
            bezier(this.begin.x, this.begin.y, c1_x, c1_y, c2_x, c2_y, this.end.x, this.end.y);
        }
    
        ....
    }