Step 4

Let's make a few updates to our application.

First, update the index.html file as follows:

  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <link rel="icon" type="image/svg+xml" href="/vite.svg" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
-     <title>Vite App</title>
+     <title>Brick Breaker</title>
    </head>
    <body>
-     <div id="app"></div>
+     <canvas id="myCanvas" width="480" height="320"></canvas>
      <script type="module" src="/main.js"></script>
    </body>
  </html>

A <canvas> is an HTML element that can draw graphics via scripting (usually JavaScript). We will be using the <canvas> at a rudimentary level. There is a lot that can be done with it. You will find a detailed tutorial and documentation for Canvas API on MDN Web Docs.

Next, replace the content of style.css with the following:

* {
  padding: 0;
  margin: 0;
}

canvas {
  background: #eee;
  display: block;
  margin: 0 auto;
}

Finally, replace the content of main.js with the following:

import "./style.css";

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.rect(20, 40, 50, 50); // x, y, width, height
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();

The above script gets hold of the <canvas> element. Then, it creates the ctx variable to store the 2D rendering context — the essential tool we can use to paint on the Canvas.

The remaining statements draw a rectangle on canvas with the specified coordinates and fill color.

Take a look at the application in the browser:

Aside-1: The canvas is a coordinate space where the origin is the top left corner.

Aside-2: Notice the statement import "./style.css" at the top of the main.js. This statement is used to employ the style.css file in our project. However, it is done in the JavaScript source code instead of the HTML file. This is an example of what currently is not (naively) supported in the browser. Nevertheless, Vite has made it possible for us to use it.

Let's also delete the following files since we won't need them!

.
└── brick-breaker
    ├── counter.js
    ├── javascript.svg