JSFiddle - React, Tailwind, and code Playground
by zoe chen
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Transitioning a fillStyle over 2.50 seconds</h4>
<!-- <br> --><!-- <button id=again>Again</button> -->
<!-- <br> --><!-- <canvas id="canvas" width=300 height=300></canvas> -->
<canvas></canvas>
CSS
body{ background-color: ivory; }
/* #canvas{border:1px solid red;} */
JavaScript
var canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
var duration = 2.50;
var rgbStart = '#fff';
var rgbEnd = '#bbb';
var opacitySteps = parseInt(60*duration);
var opacityStep = 0;
var TAU = 2 * Math.PI;
times = [];
function loop() {
var opacity = 100*(opacityStep/opacitySteps);
if(opacityStep >= opacityStep - 1){
opacity = 100;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
update();
draw();
requestAnimationFrame(loop);
}
function Ball (startX, startY, startVelX, startVelY) {
this.x = startX || Math.random() * canvas.width;
this.y = startY || Math.random() * canvas.height;
this.vel = {
x: startVelX || Math.random() * 2 - 1,
y: startVelY || Math.random() * 2 - 1
};
this.update = function(canvas) {
if (this.x > canvas.width + 50 || this.x < -50) {
this.vel.x = -this.vel.x;
}
if (this.y > canvas.height + 50 || this.y < -50) {
this.vel.y = -this.vel.y;
}
this.x += this.vel.x;
this.y += this.vel.y;
};
this.draw = function(ctx, can) {
ctx.beginPath();
ctx.globalAlpha = .4;
ctx.fillStyle = '#448fda';
ctx.arc((0.5 + this.x) | 0, (0.5 + this.y) | 0, 3, 0, TAU, false);
ctx.fill();
}
}
var balls = [];
for (var i = 0; i < canvas.width * canvas.height / (65*65); i++) {
balls.push(new Ball(Math.random() * canvas.width, Math.random() * canvas.height));
}
var lastTime = Date.now();
function update() {
var diff = Date.now() - lastTime;
for (var frame = 0; frame * 16.6667 < diff; frame++) {
for (var index = 0; index < balls.length; index++) {
balls[index].update(canvas);
}
}
lastTime = Date.now();
}
var mouseX = -1e9, mouseY = -1e9;
document.addEventListener('mousemove', function(event) {
mouseX = event.clientX;
mouseY = event.clientY;
});
function distMouse(ball) {
return Math.hypot(ball.x - mouseX, ball.y - mouseY);
}
function draw() {
...