How To Use Html5 Canvas To Draw Rectangle And Circle

This article will tell you how to use Html5 canvas and javascript to draw a rectangle and a circle.

1. Use Html5 Canvas To Draw Rectangle Steps.

  1. Get the Html5 canvas object in javascript.
    var rectCanvas = document.getElementById(id);
  2. Modify the canvas properties such as width, height, style, etc.
    rectCanvas.width = windowWidth;
    
    rectCanvas.style.display = 'block';
  3. Get the 2d context object from the canvas object.
    var ctx = rectCanvas.getContext('2d');
  4. Set the rectangle fill color.
    ctx.fillStyle = "yellow";
  5. Clear the rectangle in the canvas.
    ctx.clearRect(rectX, rectY, rectWidth, rectHeight);
  6. Fill the rectangle in the canvas with the specified color.
    ctx.fillRect(rectX, rectY, rectWidth, rectHeight)
  7. Set the stroke rectangle border color.
    ctx.strokeStyle = "blue";
  8. Set the stroke rectangle border line width.
    ctx.lineWidth = strokeBorderLineWidth;
  9. Draw the stroke rectangle with the provided border color and line width.
    ctx.strokeRect(rectX, rectY, rectWidth, rectHeight)
  10. Below is the example rectangle image.
    html5-canvas-draw-rectangle-example

2. Use Html5 Canvas To Draw Circle Steps.

  1. Get the Html5 canvas object by id.
    var circleCanvas = document.getElementById(id);
  2. Modify the canvas object attributes.
    circleCanvas.width = window.innerWidth;
    circleCanvas.height = window.innerHeight;
    circleCanvas.style.display = "block";
  3. Get the canvas 2d context object.
    var ctx = circleCanvas.getContext('2d');
  4. Call the context object’s beginPath() method to create the path.
    ctx.beginPath();
  5. Draw the radians or circle using the context object’s arc() method.
    ctx.arc(circleCenterX, circleCenterY, circleRadius, startAngle, endAngle, true);
  6. Close path by invoking the context object’s closePath() method.
    ctx.closePath();
  7. Set the circle color.
    ctx.fillStyle = "red";
  8. Fill the circle with the above color.
    ctx.fill();
  9. Set the stroke circle border color.
    ctx.strokeStyle = "green";
  10. Set the stroke circle border line width.
    ctx.lineWidth = 10;
  11. Draw the stroke circle.
    ctx.stroke();
  12. Below is the circle image.
    html5-canvas-draw-circle-example-1
  13. There is also another example that shows how to draw multiple circles using Html5 canvas, below is the example image.
    html5-canvas-draw-multiple-circles-example

3. Html5 Use Canvas To Draw Rectangle & Circle Examples.

  1. The example demo video URL is https://youtu.be/PbOhUrss1QE.
  2. This example contains 2 files html5-canvas-draw-rectangle-circle.html, html5-canvas-draw-rectangle-circle.js.
  3. On the Html file’s onload event, it will call the initialize_canvas() method to hide all the Html5 canvas on the web page.
  4. When you click the Draw button, it will draw a rectangle or circle below the button, and the button’s text will be changed to Remove. When you click the Remove button, it will hide the rectangle or circle canvas.
  5. html5-canvas-draw-rectangle-circle.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>How To Use Html5 Canvas To Draw Rectangle And Circle</title>
    <script type="text/javascript" src="html5-canvas-draw-rectangle-circle.js" charset="utf-8"></script>
    
    <style>
    canvas{
        display:block;
    }
    </style>
    
    </head>
    <body onload="initialize_canvas()">
    
    <h3>Example Of Draw Rectangle Use Html5 Canvas.</h3>
    <div>
        <input type="button" id="draw-rectangle-button" value="Draw Rectangle" onclick="drawRectangle('rectangle-canvas', this)" />
        <canvas id="rectangle-canvas"></canvas>
    </div>
    
    
    <h3>Example Of Draw Circle Use Html5 Canvas.</h3>
    <div>
        <input type="button" id="draw-circle-button" value="Draw Circle" onclick="drawCircle('circle-canvas', this)" />
        <canvas id="circle-canvas"></canvas>
    </div>
    
    <h3>Example Of Draw Multiple Circles Use Html5 Canvas.</h3>
    <div>
        <input type="button" id="draw-multiple-circles-button" value="Draw Multiple Circles" onclick="drawMultipleCircles('multiple-circles-canvas', this)" />
        <canvas id="multiple-circles-canvas"></canvas>
    </div>
    </body>
    </html>
  6. html5-canvas-draw-rectangle-circle.js.
    /**
     * 
     */
    
    // Initialize all the Html canvas objects on the Html page.
    function initialize_canvas(){
        
        // Get all the canvas object list.
        canvasList = document.getElementsByTagName('canvas');
        
        // Get the canvas object list length.
        length = canvasList.length;
        
        // Loop all the canvas objects in the list.
        for(var i=0; i < length; i++){
            
            // Get each cnavas object.
            canvasObj = canvasList[i];
            // Hide the canvas object by setting it's display style attribute to 'none'.
            canvasObj.style.display = 'none';
        }
    }
    
    /*
    This function demo how to draw a rectangle using canvas.
     */
    function drawRectangle(id, src){
            
        /*  
        Calculate the destination rectangle object left, top, width, height values.
        */
        // The rectangle width and height percentage number of the window's width and height.
        rectSizePercentage = 0.3;
        
        // Get the web browser window's width, height value.
        windowWidth = window.innerWidth;
        windowHeight = window.innerHeight;
        
        // Set the stroke border line width.
        strokeBorderLineWidth = 10;
        
        // Get the rectangle left, top coordinate value.
        rectX = strokeBorderLineWidth;
        rectY = strokeBorderLineWidth;
        // Calculate the rectangle width and height value.
        rectWidth = parseInt(windowWidth*rectSizePercentage);
        rectHeight = parseInt(windowHeight*rectSizePercentage);
        
        // Get the Html5 Canvas object.
        var rectCanvas = document.getElementById(id);
        // If not found the Canvas object then return false.
        if(rectCanvas==null){
            
            return false;
            
        }
        
        // Get the canvas display style value.
        canvasDisplay = rectCanvas.style.display;
        
        if(canvasDisplay == 'none'){
            
            src.value = "Remove Rectangle";
            
            // You should first modify the Canvas object attributes such as width, height, style.
            // Then you can call the canvasObject.getContext('2d') to get the Canvas context object.
            // If you modify the Canvas object's attributes after you get the Canvas object's context, 
            // then you will find the change does not take effect.
            rectCanvas.width = windowWidth;
            rectCanvas.height = windowHeight*(rectSizePercentage + 0.05);
            // Set the canvas object's display style to 'block' to display it.
            rectCanvas.style.display = 'block';	
            
            // Get the Canvas context object after modify it's attributes.
            var ctx = rectCanvas.getContext('2d');
            
            // Then you can modify the context attribute.
            ctx.fillStyle = "yellow";
            
            // You should clear canvas after you change it's size to avoid draw black color canvas issue.
            ctx.clearRect(rectX, rectY, rectWidth, rectHeight);
            
            // Draw the rectangle and fill the color.
            ctx.fillRect(rectX, rectY, rectWidth, rectHeight)
            
            // Set the stroke rectangle ( rectamgle without fill color and only has a border ) style color.
            ctx.strokeStyle = "blue";
            
            // Set the stroke rectangle border line width.
            ctx.lineWidth = strokeBorderLineWidth;
            
            // Draw the stoke rectangle.
            ctx.strokeRect(rectX, rectY, rectWidth, rectHeight)
            
            console.log('window.innerWidth = ' + window.innerWidth);
            
            console.log('window.innerHeight = ' + window.innerHeight);
            
            console.log('rectX = ' + rectX);
            
            console.log('rectY = ' + rectY);
            
            console.log('rectWidth = ' + rectWidth);
            
            console.log('rectHeight = ' + rectHeight);
            
        }else if(canvasDisplay == 'block'){
            
            src.value = "Draw Rectangle";
            
            rectCanvas.style.display = 'none';
        }
    }
    
    
    /*
    This function demo how to draw a circle using canvas.
     */
    function drawCircle(id, src){
        
        // Get the Html5 Canvas object.
        var circleCanvas = document.getElementById(id);
        // If not found the Canvas object then return false.
        if(circleCanvas==null){
            
            return false;
            
        }
        
        // Get the canvas display style value.
        canvasDisplay = circleCanvas.style.display;
        
        if(canvasDisplay == 'none'){
            
            circleCanvas.width = window.innerWidth;
            circleCanvas.height = window.innerHeight*0.3;
            circleCanvas.style.display = "block";	
            
            src.value = "Remove Circle";
            
            // Get the Canvas context object after modify it's attributes.
            var ctx = circleCanvas.getContext('2d');
            
            // Call the context object's beginPath() method to create the path.
            ctx.beginPath();
            
            // Define the circle center point coordinates.
            circleCenterX = 100;
            circleCenterY = 100;
            circleRadius = 90;
            startAngle = 0;
            endAngle = Math.PI * 2;
            
            // Draw the radians or circle using the context object's arc() method.
            ctx.arc(circleCenterX, circleCenterY, circleRadius, startAngle, endAngle, true);
            
            // Close path by invoking the context object's closePath() method.
            ctx.closePath(); 
            
            // Set the circle color.
            ctx.fillStyle = "red";
            
            // Fill the circle with the above color.
            ctx.fill();	
            
            // Set the stroke circle border color.
            ctx.strokeStyle = "green";
            
            // Set the stroke circle border line width.
            ctx.lineWidth = 10;
            
            // Draw the stroke circle.
            ctx.stroke();
            
        }else if(canvasDisplay == 'block'){
            
            src.value = "Draw Circle";
            
            circleCanvas.style.display = 'none';
        }
        
    }
    
    
    /*
    This function demo how to draw multiple circles using canvas.
     */
    function drawMultipleCircles(id, src){
        
        // Get the canvas object first.
        var canvas = document.getElementById(id);
        
        if(canvas==null){
            return false;
        }
        
        // Get the canvas display style value.
        canvasDisplay = canvas.style.display;
        
        if(canvasDisplay == 'none'){
            
            canvas.width = window.innerWidth*0.5;
            canvas.height = window.innerHeight*0.5;
            canvas.style.display = "block";	
            
            src.value = "Remove Multiple Circles";
            
            // Get the Canvas context object after modify it's attributes.
            var ctx = canvas.getContext('2d');
            
            ctx.fillStyle = "blue";
            
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            
            for(var i=0;i<10;i++)
            {
                // Call the context object's beginPath() method to create the path.
                ctx.beginPath();
            
                // Define the circle center point coordinates.
                circleCenterX = i*25;
                circleCenterY = i*25;
                circleRadius = i*10;
                startAngle = 0;
                endAngle = Math.PI * 2;
            
                // Draw the radians or circle using the context object's arc() method.
                ctx.arc(circleCenterX, circleCenterY, circleRadius, startAngle, endAngle, true);
            
                // Close path by invoking the context object's closePath() method.
                ctx.closePath(); 
            
                // Set the circle color.
                ctx.fillStyle = "yellow";
            
                // Fill the circle with the above color.
                ctx.fill();	
            }
    
            
        }else if(canvasDisplay == 'block'){
            
            src.value = "Draw Multiple Circles";
            
            canvas.style.display = 'none';
        }
    }

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.