Trying to code an nth order bezier in javascript on canvas for a project. I want to be able to have the user press a button, in this case 'b', to select each end point and the control points. So far I am able to get the mouse coordinates on keypress and make quadratic and bezier curves using the built in functions. How would I go about making code for nth order?
Here's a Javascript implementation of nth order Bezier curves:
// setup canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx.fillText("INSTRUCTIONS: Press the 'b' key to add points to your curve. Press the 'c' key to clear all points and start over.", 20, 20);
// initialize points list
var plist = [];
// track mouse movements
var mouseX;
var mouseY;
document.addEventListener("mousemove", function(e) {
mouseX = e.clientX;
mouseY = e.clientY;
});
// from: http://rosettacode.org/wiki/Evaluate_binomial_coefficients#JavaScript
function binom(n, k) {
var coeff = 1;
for (var i = n - k + 1; i <= n; i++) coeff *= i;
for (var i = 1; i <= k; i++) coeff /= i;
return coeff;
}
// based on: https://stackoverflow.com/questions/16227300
function bezier(t, plist) {
var order = plist.length - 1;
var y = 0;
var x = 0;
for (i = 0; i <= order; i++) {
x = x + (binom(order, i) * Math.pow((1 - t), (order - i)) * Math.pow(t, i) * (plist[i].x));
y = y + (binom(order, i) * Math.pow((1 - t), (order - i)) * Math.pow(t, i) * (plist[i].y));
}
return {
x: x,
y: y
};
}
// draw the Bezier curve
function draw(plist) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var accuracy = 0.01; //this'll give the 100 bezier segments
ctx.beginPath();
ctx.moveTo(plist[0].x, plist[0].y);
for (p in plist) {
ctx.fillText(p, plist[p].x + 5, plist[p].y - 5);
ctx.fillRect(plist[p].x - 5, plist[p].y - 5, 10, 10);
}
for (var i = 0; i < 1; i += accuracy) {
var p = bezier(i, plist);
ctx.lineTo(p.x, p.y);
}
ctx.stroke();
ctx.closePath();
}
// listen for keypress
document.addEventListener("keydown", function(e) {
switch (e.keyCode) {
case 66:
// b key
plist.push({
x: mouseX,
y: mouseY
});
break;
case 67:
// c key
plist = [];
break;
}
draw(plist);
});
html,
body {
height: 100%;
margin: 0 auto;
}
<canvas id="canvas"></canvas>
This is based on this implementation of cubic Bezier curves. In your application, it sounds like you'll want to populate the points
array with user-defined points.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With