Canvas Draw Rectangles
How to Draw a Rectangle
To draw a rectangle, follow these steps
- canvas - Assigning the canvas element to a variable.
- ctx - Assigning the 2d rendering context to another variable by calling the
getContext('2d')
method. - rect() - Use
rect()
canvas method to draw a rectangle shape (object is invisible here). - fill() - Use
fill()
canvas method to fill the object with the currentfillStyle
. The defaultfillStyle
color is 'black'.
Example
HTML Online Editor
<!DOCTYPE html>
<html lang="en-US">
<body>
<canvas id="point" width="200" height="100">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("point");
var ctx = canvas.getContext("2d");
ctx.rect(0, 0, 150, 75);
ctx.fill();
</script>
</body>
</html>
Syntax
ctx.rect(x, y, width, height)
Attributes Value
Value | Explanation |
---|---|
x | Specifies the x-axis coordinate of the rectangle's starting point. |
y | Specifies the y-axis coordinate of the rectangle's starting point. |
width | Specifies the rectangle's width.
|
height | Specifies the rectangle's height.
|
How to Custom Color the Rectangle
To custom color the rectangle, follow these steps
- canvas - Assigning the canvas element to a variable.
- ctx - Assigning the 2d rendering context to another variable by calling the
getContext('2d')
method. - fillStyle - Use
fillStyle
canvas property to specify the color to use inside shapes (any shape). - fillRect() - Use
fillRect()
canvas method to draws a rectangle that is filled according to the currentfillStyle
.
Example
HTML Online Editor
<!DOCTYPE html>
<html lang="en-US">
<body>
<canvas id="point" width="200" height="100">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("point");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#339933";
ctx.fillRect(0, 0, 150, 75);
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 93% of Canvas Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in Canvas.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.