JSFiddle - React, Tailwind, and code Playground
by bemuse
HTML
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.querySelector("#canvas");
var context = canvas.getContext("2d");
var xPos = -100;
var yPos = 170;
var motionTrailLength = 10;
var positions = [];
function storeLastPosition(xPos, yPos) {
// push an item
positions.push({
x: xPos,
y: yPos
});
//get rid of first item
if (positions.length > motionTrailLength) {
positions.shift();
}
}
function update() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < positions.length; i++) {
var ratio = (i + 1) / positions.length;
drawCircle(positions[i].x, positions[i].y, ratio);
}
drawCircle(xPos, yPos, "source");
storeLastPosition(xPos, yPos);
// update position
if (xPos > 600) {
xPos = -100;
}
xPos += 10;
requestAnimationFrame(update);
}
update();
function drawCircle(x, y, r) {
if (r == "source") {
r = 1;
} else {
r /= 4;
}
context.beginPath();
context.arc(x, y, 50, 0, 2 * Math.PI, true);
context.fillStyle = "rgba(204, 102, 153, " + r + ")";
context.fill();
}