Using The Javascript fillRect() Method To Create An Interactive Keyboard Controlled Rectangle Inside A Canvas

Published on | by
Reza Baharvand
Updated on
Image for Using The Javascript fillRect() Method To Create An Interactive Keyboard Controlled Rectangle Inside A Canvas

Introduction

The fillRect() method renders 2d context on HTML <canvas> element. You can create simple or complex shapes by defining ( x, y, width, height) on the canvas.

The fillRect() method, draws a filled rectangle with that starting point at (x,y) and stretches by the defined width and height.

// syntax fillRect(x, y, width, height);

You can define the style by the fillStyle attribute.

In this tutorial, you will create an interactive moving rectangle inside a canvas using HTML, CSS, and Javascript. This includes:

  • Creating a canvas in the HTML
  • Drawing a blue rectangle inside the canvas, using the fillRect() method
  • Adding controller buttons to move the blue rectangle
  • Adding keyboard event listeners to record movements

Demo

You can find the demo on codepen.

Step 1 — Creating The Canvas

Start a new codepen project and create a canvas by adding the following code inside the HTML:

<canvas id="canvas" width="320" height="320"></canvas>

This code initializes a canvas with the id="canvas", height and width of 320px.

Step 2 — Rendering A Rectangle Inside The Canvas

To render a rectangle inside the canvas, you must select the canvas element and render a 2d shape using the fillRect() method.

Inside your Javascript file add this code block:

const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let x, y, width, height, color; x = 10; y = 10; width = 40; height = 40; color = "#0096C7"; ctx.fillStyle = color; ctx.fillRect(x, y, width, height);

You have selected the <canvas> by its id. Then created a 2d context and assigned a value to x, y, width, height, and color.

The fillStyle property specifies the color and fillRect() draws the rectangle based on the provided values.

Step 3 — Adding The Controller Buttons To The HTML

To control the movement of the blue rectangle, you will need to add buttons to the page so the rectangle can move in 4 directions.

Inside the HTML file, add this code below the <canvas> element:

<canvas id="canvas" width="320" height="320"></canvas> <div> <h3>Use Your Keyboard To Move The Rectangle</h3> <button>&uarr; Up</button> <button>&rarr; Right</button> <button>&darr; Down</button> <button>&larr; Left</button> </div>

Step 4 — Adding Keyboard Event Listeners In Javascript

You will need to move the rectangle every time one of the four keys is pressed down. The only tricky part is clearing the previous state of the rectangle after pressing each key. The clearRect() method sets the pixels in the rectangle to transparent. The syntax is similar to fillRect() method.

// syntax clearRect(x, y, width, height);

To add the event listener, you have to write a function that moves the rectangle in the direction you wanted:

const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let x, y, width, height, color; x = 10; y = 10; width = 40; height = 40; color = "#0096C7"; ctx.fillStyle = color; ctx.fillRect(x, y, width, height); // Key Event Listener window.addEventListener("keydown", (event) => { event.code == "ArrowUp" ? (y -= 20) : event.code == "ArrowRight" ? (x += 20) : event.code == "ArrowDown" ? (y += 20) : event.code == "ArrowLeft" ? (x -= 20) : x; ctx.clearRect(0, 0, 320, 320); ctx.fillRect(x, y, width, height); });

The function listens to the keydown and moves the rectangle in the wanted direction accordingly. You can also replace the ternary operator with if...else syntax if you wish to.

However, if you press the arrow keys long enough, the rectangle goes off the canvas! To prevent this from happening you have to refine the if...else conditions and limit the x and y.

const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); let x, y, width, height, color; x = 10; y = 10; width = 40; height = 40; color = "#0096C7"; ctx.fillStyle = color; ctx.fillRect(x, y, width, height); // Key Event Listener window.addEventListener("keydown", (event) => { event.code == "ArrowUp" && y > 10 ? (y -= 20) : event.code == "ArrowRight" && x <= 260 ? (x += 20) : event.code == "ArrowDown" && y <= 260 ? (y += 20) : event.code == "ArrowLeft" && x > 10 ? (x -= 20) : x; ctx.clearRect(0, 0, 320, 320); ctx.fillRect(x, y, width, height); });

At this point, your little app is functional. In the next step, you will style it to make it look a bit better using CSS.

Step 5 — Styling Your App

In this step, you will center everything inside the <body>, and add a border to the canvas.

body { font-family: sans-serif; margin: 0; height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; } #canvas { border: 1px solid #ccc; }

Conclusion

In this tutorial, You created an interactive Tetris-like app, Rendered a rectangle inside the canvas, and made it move around by pressing arrow keys on your keyboard.


Recent Posts

Image for Coin Flip Simulator With Javascript And CSS Animations

Coin Flip Simulator With Javascript And CSS Animations

In this tutorial, you will learn to build a small app to toss a coin using HTML, CSS, and Javascript. The possible outcomes after flipping a coin are either "Head" or "tail". The probability of getting head or tail is 50%.

Image for Use Math.PI To Calculate Area And Circumference Of A Circle

Use Math.PI To Calculate Area And Circumference Of A Circle

The "Math.PI" property returns the PI "π" constant, approximately equal to 3.14159. For example, you can calculate the circumference and surface area of a circle using "Math.PI".

Image for Check If A Function Exists Before Calling With The typeof Operator

Check If A Function Exists Before Calling With The typeof Operator

If you are sharing scripts from different modules or you have a large codebase, you can use the `typeof` operator to check if a function exists.

Image for Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

The "toggle()" is a method of the "DOMTokenList". It removes something like a "class" name from the list, and returns "false". If the "class" name does not exist, it will add it to the list and return "true".