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.
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.
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" >w3wiki</ 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 >
|
CSS
@import url (
'https://fonts.googleapis.com/css2?family=Poppins&display=swap' );
body {
font-family : 'Poppins' , sans-serif ;
}
#canvas 1 -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 : 100 vh;
flex- direction : column;
flex-wrap: wrap;
}
|
Javascript
const canvas1Element =
document.getElementById( "canvas1-id" ).getContext( "2d" );
canvas1Element.fillStyle = "green" ;
canvas1Element.fillRect(50, 50, 200, 200);
|
HTML Canvas Drawing with fillStyle
Example 2: In this example, we will see the implementation of the Canvas drawing with strokeStyle and lineWidth.
HTML
<!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" >w3wiki</ p >
< h1 >HTML Canvas Drawing</ h1 >
< div >
< canvas id = "canvas1-id"
width = "300"
height = "300" >
</ canvas >
</ div >
</ div >
< script src = "script.js" ></ script >
</ body >
|
CSS
@import
url ( 'https://fonts.googleapis.com/css2?family=Poppins&display=swap' );
body {
font-family : 'Poppins' , sans-serif ;
}
#canvas 1 -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 : 100 vh;
flex- direction : column;
flex-wrap: wrap;
}
|
Javascript
const canvas2Element =
document.getElementById( "canvas1-id" )
const ele =
canvas2Element.getContext( "2d" );
ele.strokeStyle = "blue" ;
ele.lineWidth = 2;
ele.strokeRect(50, 50, 180, 180)
|
HTML Canvas Drawing with strokeStyle
Contact Us