Skip to content

Instantly share code, notes, and snippets.

@omaraflak
Created October 16, 2022 19:17
Show Gist options
  • Save omaraflak/59c8de2a14771177599934001e380cf7 to your computer and use it in GitHub Desktop.
Save omaraflak/59c8de2a14771177599934001e380cf7 to your computer and use it in GitHub Desktop.
JS canvas get started template
<canvas id="canvas"></canvas>
<script>
const WIDTH = 500
const HEIGHT = 500
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
canvas.width = WIDTH
canvas.height = HEIGHT
draw_rectangle = (x, y, w, h, color) => {
ctx.fillStyle = color
ctx.fillRect(x, y, w, h)
}
clear_canvas = () => draw_rectangle(0, 0, WIDTH, HEIGHT, "black")
update_point = (p) => {
p.x += p.vx
p.y += p.vy
if (p.x <= 0 || p.x + p.size > WIDTH) {
p.vx *= -1
}
if (p.y <= 0 || p.y + p.size > HEIGHT) {
p.vy *= -1
}
}
draw_point = (p) => draw_rectangle(p.x, p.y, p.size, p.size, p.color)
const point = {
"x": Math.random() * WIDTH,
"y": Math.random() * HEIGHT,
"vx": 6 * Math.random(),
"vy": 6 * Math.random(),
"size": 5,
"color": "yellow"
}
update = () => {
clear_canvas()
update_point(point)
draw_point(point)
requestAnimationFrame(update)
}
update()
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment