HTML Canvas Drawing facilitates the <canvas> element, along with Properties that help to draw on the HTML canvas. The various properties, attributes & events can be used with <canvas> element. Utilizing JavaScript, we can manipulate the canvas element to draw shapes, paths, and images, providing a versatile platform for interactive and engaging web content.
Syntax
ctx1.fillRect(50, 50, 200, 200); ctx2.strokeRect(50, 50, 180, 180);
Example: In this example, we will see the implementation of the Canvas drawing with fillStyle.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>HTML Canvas Drawing</title>
<link rel="stylesheet"
href="style.css">
</head>
<body>
<div class="box">
<p class="gfg">GeeksforGeeks</p>
<h1>HTML Canvas Drawing</h1>
<div>
<canvas id="canvas1-id"
width="300"
height="300">
</canvas>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
@import url(
'https://fonts.googleapis.com/css2?family=Poppins&display=swap');
body {
font-family: 'Poppins', sans-serif;
}
#canvas1-id {
border: 2px solid black;
border-radius: 5px;
}
.gfg {
color: green;
font-size: 45px;
}
.text-area {
font-size: 20px;
}
.box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
flex-wrap: wrap;
}
const canvas1Element =
document.getElementById("canvas1-id").getContext("2d");
canvas1Element.fillStyle = "green";
canvas1Element.fillRect(50, 50, 200, 200);
Output:

Example 2: In this example, we will see the implementation of the Canvas drawing with strokeStyle and lineWidth.
<!DOCTYPE html>
<html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>HTML Canvas Drawing</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box">
<p class="gfg">GeeksforGeeks</p>
<h1>HTML Canvas Drawing</h1>
<div>
<canvas id="canvas1-id"
width="300"
height="300">
</canvas>
</div>
</div>
<script src="script.js"></script>
</body>
/* Write CSS Here */
@import
url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');
body {
font-family: 'Poppins', sans-serif;
}
#canvas1-id {
border: 2px solid black;
border-radius: 5px;
}
.gfg {
color: green;
font-size: 45px;
}
.text-area {
font-size: 20px;
}
.box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
flex-wrap: wrap;
}
const canvas2Element =
document.getElementById("canvas1-id")
const ele =
canvas2Element.getContext("2d");
ele.strokeStyle = "blue";
ele.lineWidth = 2;
ele.strokeRect(50, 50, 180, 180)
Output:
