'Importing a class in vanilla JavaScript isn't working
I was making a cool graphic for my website when I got this weird bug. I import a class called 'Particle' from particle.js and I also give it HTML5 Canvas' 2dRenderingContextAPI too. Please take a look at my code and tell where I went wrong. I expect a black rectangle to be drawn on Canvas.
//This is the file attached to the document
//Imports
import Particle from "./particle.js";
//Global Variables
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particle = new Particle(ctx);
//Animation Loop
function animate() {
ctx.fillStyle = 'rgba(0, 0, 139, 0.2)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
particle.draw();
requestAnimationFrame(animate);
}
animate();
body {
margin: 0;
padding: 0;
box-sizing: border-box;
overflow: hidden;
}
#canvas1 {
height: 100vh;
width: 100vw;
background: darkblue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bouncing particles</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas1"></canvas>
<script src="script.js" type="module"></script>
</body>
</html>
And this is my particle.js file:
//This is particle.js
export default class Particle {
constructor(ctx) {
this.height = 100;
this.width = 100;
this.ctx = ctx;
}
draw() {
this.ctx.fillRect(50, 50, this.height, this.width);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
