Skip to content

Instantly share code, notes, and snippets.

@pvernier
Last active March 11, 2018 19: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 pvernier/31b9bc0c95b76a8487535cc9ccd3d1d3 to your computer and use it in GitHub Desktop.
Save pvernier/31b9bc0c95b76a8487535cc9ccd3d1d3 to your computer and use it in GitHub Desktop.
A simple canvas animation...
license: gpl-3.0
height: 500
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<canvas id="myCanvas" width="500px" height="500px"></canvas>
<script>
getRandomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
drawPoint = () => {
ctx.fillStyle = '#b2182b'
ctx.beginPath()
ctx.arc(init.x, init.y, 5, 0, 2 * Math.PI)
ctx.fill()
}
canvas = document.getElementById("myCanvas")
ctx = canvas.getContext("2d")
const width = canvas.width
const height = canvas.height
ctx.strokeRect(0, 0, width, height);
const init = { x: width / 2, y: height / 2 }
const anim = setInterval(() => {
// Clear the canvas
ctx.clearRect(0, 0, width, height)
// Fill in the canvas in grey
ctx.fillStyle = '#4d4d4d'
ctx.fillRect(0, 0, width, height);
// Draw a white circle that contains the point
const radius = Math.sqrt(Math.abs(init.x - width / 2) ** 2 + Math.abs(init.y - height / 2) ** 2) + 5
ctx.beginPath()
ctx.arc(width / 2, height / 2, radius, 0, 2 * Math.PI)
ctx.fillStyle = 'white'
ctx.fill()
// Draw the point
drawPoint()
// Update the center of the point
init.x += getRandomInt(-5, 5)
init.y += getRandomInt(-5, 5)
// Stop the animation if the point touches an edge of the canvas
if (init.x <= 0 || init.x >= width || init.y <= 0 || init.y >= height) {
clearInterval(anim)
}
}, 80)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment