The below code demonstrates designing a rectangle area on an HTML page without using scripting language. Here height and width attributes defines size of the rectangle.
[html]<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="250" height="150" style="border:3px solid #2E2EFE;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</body>
</html>
[/html]
Result
By running the above code in a preferred browser following output appears.
Now, Add JavaScript for the code as shown below.
[html]<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="250" height="150" style="border:2px solid #2E2E2E;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF4000";
ctx.fillRect(0,0,200,100);
</script>
</body>
</html>
[/html]
Result
By running the above code in a preferred browser following output appears.
Following are the three methods to draw a rectangle in canvas.
- fillRect(x,y,width,height)
The method used to fill the rectangular.
- strokeRect(x,y,width,height)
The method used to draw rectangular outline.
- clearRect(x,y,width,height)
The method used to clear the required area and make it as transparent.
x,y defines position on the Canvas for all the three methods. The code below demonstrate the use of all the 3 methods.
[html]<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 200px;
height:200px;
margin: 0px auto;
}
</style>
<script type="text/javascript">
function drawShape(){
// Get the canvas element using the DOM
var canvas = document.getElementById('rectangle');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext){
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
ctx.fillRect(25,25,200,200);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
}
else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id="test" onload="drawShape();">
<canvas id="rectangle"></canvas>
</body>
</html>
[/html]
Result
By running the above code in a preferred browser following output appears.