Thursday, 23 September 2021

How to join 2 Bezier curves smoothly & continuously with HTML5 Canvas

I'm trying to join two separate bezier curves into one continuous curve. Currently, what I have looks like this:

Two separate bezier curves

The problem is that they aren't joined, so the points at which they meet look pointy/sharp instead of curvy and smooth. I've looked into documentation for joining bezier curves in P5.js, but am unsure of how to translate this into HTML5 Canvas. How do I join these two bezier curves so that they look like one smooth and continuous curve?

This is my code:

const canvas = document.getElementById('canvas');
const c = canvas.getContext("2d");
width = 800;
height = 500;
canvas.width = width;
canvas.height = height;
let face;
let centerX = width / 2;
let centerY = height / 3;

setup();

function setup() {
    c.clearRect(0, 0, canvas.width, canvas.height);
    face = new Face();
    draw();
};

function draw() {
    setBackground(`rgba(250, 250, 250, 1)`);
    c.beginPath();
    c.moveTo(centerX - face.hsx, centerY + face.hsy);
    c.bezierCurveTo(centerX - face.hcp1x / 10, centerY - face.hsy2,
        centerX + face.hcp1x / 10, centerY - face.hsy2,
        centerX + face.hsx, centerY + face.hsy);
    c.moveTo(centerX - face.hsx, centerY + face.hsy);
    c.bezierCurveTo(centerX - face.hcp1x, centerY + face.hcp1y,
        centerX + face.hcp1x, centerY + face.hcp1y,
        centerX + face.hsx, centerY + face.hsy);
    c.stroke();
    c.fillStyle = (`rgba(25, 250, 211, 0)`);
    c.fill();
}

function setBackground(color) {
    c.fillStyle = color;
    c.fillRect(0, 0, width, height);
}

function Face() {
    this.hsx = 150; 
    this.hsy = 0;
    this.hsy2 = 120;
    this.hcp1x = 120;
    this.hcp1y = 250; 
}


from How to join 2 Bezier curves smoothly & continuously with HTML5 Canvas

No comments:

Post a Comment