JSFiddle - React, Tailwind, and code Playground
canvas: fly of the ball
by hronic
HTML
<canvas id="canvas" width="400" height="400"></canvas>
CSS
#canvas {
border: 1px dashed #cecece;
}
JavaScript
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
function Ball(x, y, r, dx, dy, style) {
this.x = x;
this.y = y;
this.r = r;
this.dx = dx;
this.dy = dy;
this.style = style;
this.line = style;
this.update = function() {
// Acceleration toward the mouse
var diffX = mouseX - this.x;
var diffY = mouseY - this.y;
var dist2 = diffX * diffX + diffY * diffY + 1;
var ddx = accel * Math.abs(diffX) *
diffX / dist2;
var ddy = accel * Math.abs(diffY) *
diffY / dist2;
// Bounce off the edges
if (this.x - this.r + this.dx < 0 ||
this.x + this.r + this.dx > w) {
this.dx = -this.dx * friction;
} else {
this.dx += ddx;
}
if (this.y - this.r + this.dy < 0 ||
this.y + this.r + this.dy > h) {
this.dy = -this.dy * friction;
} else {
this.dy += ddy;
}
this.x = this.x + this.dx;
this.y = this.y + this.dy;
// Enforce the boundaries
this.x = Math.max(this.r, this.x);
this.x = Math.min(w - this.r, this.x);
this.y = Math.max(this.r, this.y);
this.y = Math.min(h - this.r, this.y);
this.stroke();
};
this.stroke = function() {
c.beginPath();
//c.lineWidth = 3;
//c.strokeStyle = this.style;
c.fillStyle = this.style;
c.arc(this.x, this.y, this.r,
0, Math.PI * 2);
c.closePath();
c.fill();
};
}
function rancol(){
var limit = 255;
var r = Math.floor(Math.random() * limit);
var g = Math.floor(Math.random() * limit);
var b = Math.floor(Math.random() * limit);
var a = Math.random();
var rgba = [r,g,b,a].join(',');
return "rgba("+rgba+")";
}
var accel = 0.1;
var friction = 0.8;
var mouseX = 0;
var mouseY = 0;
var timeStep = 25; // In milliseconds
var w = c.canvas.width;
var h = c.canvas.height;
var cmTID;
function updateAll() {
c.clearRect(0, 0, w, h);
for (var i = 0; i < balls.length; i = i + 1)...