Interactive HTML Canvas

Assignment 5:

Let's create an interactive canvas page! Think of an idea that interests you implement it. Start with this code and build on it to make something you enjoy playing with!

Please incorporate at least 2 of the 3 here:

  • Respond to user input: mouse click and/or mouse movement
  • Randomness: color and/or position
  • Looping

Please turn in 3 screenshots, and/or your code as a google drive attachment to an email, or on Microsoft teams. Due before next class, Monday May 23.

index.html

1<!DOCTYPE html>
2<html lang="en">
3  <head>
4    <meta charset="UTF-8">
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <meta http-equiv="X-UA-Compatible" content="ie=edge">
7    <title>Canvas</title>
8    <link rel="stylesheet" href="style.css">
9  </head>
10  <body>
11  <canvas id="myCanvas"></canvas>
12	<script src="script.js"></script>
13  </body>
14</html>

script.js

1//SETUP
2let randomNumber = function(range){
3	let result = Math.floor(Math.random()*range);
4	return result;
5}
6
7let randomColor = function(){
8	let r = randomNumber(256);
9	let g = randomNumber(256);
10	let b = randomNumber(256);
11	let colorString = "rgb(" + r + "," + g + "," + b + ")";
12	return colorString;
13}
14
15let mouseClickListener = function(event){
16  //user just clicked
17  let x = event.x;
18  let y = event.y;
19  console.log(x,y);
20  randomBox(x,y);
21}
22
23let eraseCanvas = function(){
24	ctx.clearRect(0,0,window.innerWidth,window.innerHeight);
25}
26
27let randomBox = function(x,y){
28	let boxWidth = randomNumber(200);
29	let boxHeight = randomNumber(200);
30	ctx.fillStyle = randomColor();
31	ctx.fillRect(x,y,boxWidth,boxHeight);
32}
33
34//Now we start doing stuff
35let canvas = document.querySelector("#myCanvas");
36canvas.width = window.innerWidth;
37canvas.height = window.innerHeight;
38let ctx = canvas.getContext("2d");
39
40
41//When a user CLICKS on the canvas, run the mouseClickListener function
42canvas.addEventListener("click",mouseClickListener)
43
44

style.css

1body {
2  margin: 0;
3}