Two Circles Explode
const { random, min, sqrt, cos, sin, PI } = Math
let TWO_PI = PI * 2
let minSize
document.body.style.margin = 0
document.body.style.background = 'black'
const canvas = document.body.appendChild(
document.createElement('canvas')
)
const c = canvas.getContext('2d')
addEventListener('resize', resize)
resize()
function resize() {
canvas.width = innerWidth
canvas.height = innerHeight
minSize = min(innerWidth, innerHeight)
clear()
}
function clear() {
c.fillStyle = 'rgba(0, 0, 0, .15)'
c.fillRect(0, 0, innerWidth, innerHeight)
}
let dots = []
function dot({x, y, vx, vy, rad, grav = .15}) {
let sx = x
let sy = y
let svx = vx
let svy = vy
let intersected
let partsNum = 20
let parts = []
let delay = random() * 5
let time = 0
dots.push(() => y > innerHeight)
return {
step() {
time++
if (time < delay) return
if (intersected) {
for (let i = 0; i < partsNum; i++) {
parts[i].step()
}
return
}
x += vx
y += vy
vy += grav;
c.beginPath()
c.arc(x, y, rad(), 0, 7)
c.fill()
},
reset() {
x = sx;
y = sy;
vx = svx;
vy = svy;
intersected = false
},
hit() {
if (!intersected) {
partsNum = rad() / 3
for (let i = 0; i < partsNum; i++) {
let t = random() * TWO_PI
let r = 5 + random() * 5
let size = random() * 10
parts.push(
dot({
x, y,
vx: r * cos(t),
vy: r * sin(t),
rad: () => size
})
)
}
}
intersected = true
},
get x() {
return x
},
get y() {
return y
}
}
}
const bigRad = () => minSize * .14;
let leftDot
let rightDot
function start() {
rightDot = dot({
x: innerWidth,
y: innerHeight / 2,
vx: -innerWidth * .005,
vy: -6, rad: bigRad
})
leftDot = dot({
x: 0,
y: innerHeight / 2,
vx: innerWidth * .005,
vy: -6, rad: bigRad
})
}
start()
function collide(a, b) {
const dx = a.x - b.x
const dy = a.y - b.y
const dist = sqrt(dx**2 + dy**2)
return dist <= bigRad() * 1.8
}
function loop() {
let inc = 2
clear()
c.fillStyle = 'white'
if (collide(leftDot, rightDot)) {
leftDot.hit()
rightDot.hit()
}
leftDot.step()
rightDot.step()
dots.forEach(done => {
if (done()) inc++;
})
if (dots.length > 2 && inc == dots.length) {
dots = []
start()
}
requestAnimationFrame(loop)
}
loop()
Two circles intersect and explode repeatedly… works at any browser size…