Animated catmull-rom spline drawing with forward differencing
HTML
<main>
<canvas id="canvas" width="500" height="300"></canvas>
<div>
<input type="checkbox" checked=true id="splineRegular">Regular
<input type="checkbox" checked=true id="splineForward">Forward differencing
</div>
</main>
JavaScript
// get canvas element
var canvas = document.getElementById('canvas');
// get drawing context from canvas element
var ctx = canvas.getContext("2d");
if (!canvas || !canvas.getContext) {
window.alert("No canvas or context. Your browser sucks!");
return;
}
var imgd = false;
var width = canvas.width;
var height = canvas.height;
// Try to create image data from scratch
// If that doesn't work, try to load it from the context
// If that fails too, create an array of the same size and pray
if (ctx.createImageData) {
imgd = ctx.createImageData(width, height);
} else if (ctx.getImageData) {
imgd = ctx.getImageData(0, 0, width, height);
} else {
imgd = {
'width': width,
'height': height,
'data': new Array(width * height * 4)
};
}
// get actual pixel data
var pix = imgd.data;
// Random points and directions
var points = new Array(new Array(Math.random() * width, Math.random() * height), new Array(Math.random() * width, Math.random() * height), new Array(Math.random() * width, Math.random() * height), new Array(Math.random() * width, Math.random() * height));
var directions = new Array(new Array(Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0), new Array(Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0), new Array(Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0), new Array(Math.random() * 2.0 - 1.0, Math.random() * 2.0 - 1.0));
const speed = 2.0;
const subdivision = 16.0;
function movepoints(points, directions, width, height) {
for (var i = 0; i < points.length; i++) {
points[i][0] += speed * directions[i][0];
if (points[i][0] <= 0 || points[i][0] >= width) {
directions[i][0] = -directions[i][0];
}
points[i][1] += speed * directions[i][1];
if (points[i][1] <= 0 || points[i][1] >= height) {
directions[i][1] = -directions[i][1];
}
}
}
function drawlabels(ctx, points) {
ctx.font = "12px Courier New";
ctx.fillStyle = "Black";
for (var i = 0; i < points.length; i++) {
ctx.fillText("P" + i,...