HTML5 Canvas Rectangles and Styles

Anton Lytvynov
2 min readApr 15, 2021

Let’s go deeper in understanding the basic primitives and what we can do with them

Fill the element

Let’s draw a rectangle and fill it

To fill the element we should use these two lines

context.fillStyle = "yellow"
context.fill();

Fill rectangle example

let canvas = document.getElementById('c1');
let context = canvas.getContext("2d");

window.onload = function () {
context.strokeStyle = "green";
context.lineWidth = 4;
context.lineJoin = "round";
context.fillStyle = "yellow";
context.rect(10,10, 50, 50);
context.stroke();
context.fill();
}
Filled rectangle

You can also draw a filled rectangle in the other way

context.fillStyle = "green";
context.fillRect(65, 10, 50, 50);
fillRect function

Draw rectangle without background

context.lineWidth = 1;
context.strokeStyle = "red";
context.lineJoin = "round";
context.strokeRect(120, 10, 50, 50);
Not filled rectangle

Clear function

You can remove a part with the next function

context.clearRect(5, 5, 20, 20);
Clear a part

Or clear all the canvas

context.clearRect(0, 0, 1000, 1000);

Result

You can check the code for this part here.

Result

Thank you for your attention.

Thank you for your attention.

Do you need help with web or mobile development? Feel free to contact me here.

P.S. I really appreciate your like or share 🙏.

--

--

Anton Lytvynov
Anton Lytvynov

Written by Anton Lytvynov

CEO & Founder of Lytvynov Production, Senior web developer, architect, cryptocurrencies trader, https://lytvynov-production.com

No responses yet