JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<h4>Plot along a quadratic curve</h4>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var startPoint = {
x: 50,
y: 150
};
var controlPoint = {
x: 125,
y: 20
};
var endPoint = {
x: 200,
y: 150
};
ctx.beginPath();
ctx.moveTo(startPoint.x, startPoint.y);
ctx.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
ctx.stroke();
for (var t = 0; t < 101; t += 5) {
var point = getQuadraticBezierXYatT(startPoint, controlPoint, endPoint, t / 100);
ctx.beginPath();
ctx.arc(point.x, point.y, 3, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = randomColor();
ctx.fill();
}
function getQuadraticBezierXYatT(startPt, controlPt, endPt, T) {
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;
return ({
x: x,
y: y
});
}
function randomColor() {
return ('#' + Math.floor(Math.random() * 16777215).toString(16));
}