Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
color_gradient.js
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// ctx.globalCompositeOperation = 'destination-over';
const edge = 200;
const particleScale = 20;
let drawing = false;
class Root {
constructor(x, y, color, centerX, centerY) {
this.x = x;
this.y = y;
this.color = color;
this.speedX = 0;
this.speedY = 0;
this.centerX = centerX;
this.centerY = centerY;
this.cycles = 0;
}
// THIS HAS TO BE AN ARROW FUNCTION :)
draw = () => {
// ctx.fillStyle = 'rgba(255, 255, 255)';
// ctx.fillRect(0, 0, canvas.width, canvas.height);
// ctx.strokeStyle = 'black';
// ctx.font = "30px Arial";
// ctx.fillText("Hello World", this.x, this.y);
this.speedX += (Math.random()*5 - 2.5) / 2;
this.speedY += (Math.random()*5 - 2.5) / 2;
this.x += this.speedX;
this.y += this.speedY;
this.cycles++;
const distX = this.x - this.centerX;
const distY = this.y - this.centerY;
const distance = Math.sqrt(distX**2 + distY**2);
// a decaying particle size, for fun
const radius = (-distance / edge + 1) * edge / particleScale;
if (radius > 0) {
requestAnimationFrame(this.draw); // use .bind if not using arrow functions
ctx.beginPath();
ctx.arc(this.x, this.y, radius, 0, 2*Math.PI);
// ctx.fillStyle = `hsl(${this.color}, 100%, ${(100-radius)}%)`;
ctx.fillStyle = `hsl(${this.color+this.cycles}, 80%, 50%)`;
ctx.fill();
ctx.strokeStyle = 'black';
// ctx.strokeStyle = this.color;
ctx.stroke();
}
}
}
const doArt = (event) => {
const x = event.offsetX || event.layerX || event.x;
const y = event.offsetY || event.layerY || event.y;
// try changing 1 to 3
for (let i=0; i<3; i++) {
const root = new Root(x, y, color, x, y);
root.draw();
}
}
// Update canvas size to scale with the window resize events
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// Activate on click (comment out if mousemove is enabled)
// window.addEventListener('click', doArt);
// Uncomment these lines to active 'on mouse move'
window.addEventListener('mousemove', (event) => {
if (!drawing) return;
// ctx.fillStyle = 'rgba(0, 0, 255, 0.03)';
// ctx.fillRect(0, 0, canvas.width, canvas.height);
doArt(event);
});
let color = '';
window.addEventListener('mousedown', () => {
color = Math.random()*360;
drawing = true;
});
window.addEventListener('mouseup', () => drawing = false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment