Created
August 25, 2020 07:49
-
-
Save Skoatpalace/ca71ceadf090cf8308c570d88b5b2e74 to your computer and use it in GitHub Desktop.
Canvas HTML collisions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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