WIM/WIM4.1/tp/tp4/ex2/ballon.js

108 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-05-17 12:35:25 +02:00
const canvas = document.querySelector('canvas')
canvas.width = window.innerWidth
canvas.height = window.innerHeight
const c = canvas.getContext('2d')
const circlesCount = 300
const maxRadius = 40
const circleArray = []
let areaMouse = new Array();
let aura = 150;
const colorArray = [
'#046975',
'#2EA1D4',
'#3BCC2A',
'#FFDF59',
'#FF1D47'
]
const init = () => {
circleArray.length = 0
for (let i = 0; i < circlesCount; i++) {
const radius = Math.random() *maxRadius +1 ;
const x = Math.random() * (innerWidth - radius * 2) + radius
const y = Math.random() * (innerHeight - radius * 2) + radius
const dx = (Math.random() - 0.5) * 2
const dy = (Math.random() - 0.5) * 2
circleArray.push(new Circle(x, y, dx, dy, radius))
}
}
const Circle = function(x, y, dx, dy, radius) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.radius = radius
this.minRadius = radius
this.color = colorArray[Math.floor(Math.random() * colorArray.length)]
this.draw = function() {
// A completer
c.fillStyle = this.color;
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI*2, false);
c.fill();
c.stroke();
c.closePath()
}
this.update = function() {
// A completer
this.x += dx;
this.y += dy;
if( this.x <= areaMouse["Xmax"] && this.x >= areaMouse["Xmin"] // vérifie si l'élément est autour de la souris
&& this.y <= areaMouse["Ymax"] && this.y >= areaMouse["Ymin"] )
{
this.radius = maxRadius;
}
else {
this.radius = this.minRadius;
}
if(this.x+this.radius >= canvas.width|| this.x <= this.radius) { // vérifie si on touche les murs sur les côtés
dx *= -1;
}
if(this.y+this.radius >= canvas.height || this.y <=this.radius) { // vérifie si on touche le sol ou le plafond
dy *= -1;
}
this.draw();
}
}
const animate = () => {
c.clearRect(0, 0, innerWidth, innerHeight)
for (let i = 0; i < circleArray.length; i++) {
circleArray[i].update()
}
requestAnimationFrame(animate)
}
document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
areaMouse["Xmin"] = event.clientX - aura;
areaMouse["Xmax"] = event.clientX + aura;
areaMouse["Ymin"] = event.clientY - aura;
areaMouse["Ymax"] = event.clientY + aura;
}
init()
animate()