Canvas- Draw Rectangles, Fill and Clear them

Written by @m_k_amin 13 June 2013

Because the rectangles are so common shapes that are needed a lot in 2D graphics, HTML5 Canvas has special functions for it. So you can easily draw and fill a rectangle just by defining a point for its up-left corner and then specifying its width and height. It is also easy for clear part of the context in a rectangular shape. Use the following example to figure out how all of these things can be done about Rectangles by using HTML5 Canvas element and JavaScript.

Code Snippet:

                                                
                                                <!-- this script is provided by www.html5freecode.com coded by: Kerixa Inc. -->
<!-- This Script is from www.html5freecode.com, Coded by: Kerixa Inc-->
<canvas id="myCanvas" width="400px" height="230px"></canvas>
<script>
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')

	ctx.beginPath()
    ctx.fillStyle= "lightblue"
	ctx.fillRect(20, 20, 80, 120)
	
 	ctx.beginPath()
    ctx.lineWidth= 2
	ctx.strokeRect(150, 50, 130, 50)
    ctx.strokeStyle= "Brown"
    ctx.stroke()

	ctx.beginPath()
    ctx.fillStyle= "rgba(120, 30, 10, 0.3)"
	ctx.fillRect(10, 10, 300, 150)

	ctx.beginPath()
	ctx.clearRect(80, 90, 90, 20)
</script>
<div style="text-align: left"><font face="Tahoma"><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: FOTPU
advertisement 2