Skip to content

Instantly share code, notes, and snippets.

@Skoatpalace
Created August 25, 2020 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Skoatpalace/ca71ceadf090cf8308c570d88b5b2e74 to your computer and use it in GitHub Desktop.
Save Skoatpalace/ca71ceadf090cf8308c570d88b5b2e74 to your computer and use it in GitHub Desktop.
Canvas HTML collisions
const canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
animate();
})
const distanceMiddleCircle = (x1, y1, x2, y2) => {
//racine carré de (x2-x1)² + (y2-y1)²
let xDist = x2-x1;
let yDist = y2 - y1;
return Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2));
}
class Circle {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
}
draw () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
}
}
const circle1 = new Circle(300, 300, 100, 'black');
const circle2 = new Circle(undefined, undefined, 30, 'red');
const animate = () => {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle1.draw();
canvas.addEventListener('mousemove', (e) => {
circle2.x = e.clientX;
circle2.y = e.clientY;
})
circle2.draw();
if (distanceMiddleCircle(circle1.x, circle1.y, circle2.x, circle2.y) < circle1.radius + circle2.radius) {
circle1.color = 'red';
} else {
circle1.color = 'black';
}
}
animate();
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collisions canvas</title>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment