Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to draw different shapes with canvas?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 167
    Comment on it

    Hello readers, today we will discuss canvas element for drawing different shapes like triangle and square.  Canvas element of HTML is used to draw graphics on the web page. In my example, I am using this element to draw a triangle and square.

    Here is the HTML code:

    <html>
     <body onload="drawtriangle();drawsquare();">
       
       <canvas id="triangle" width="200" height="100"></canvas>
    
       <canvas id="square" width="150" height="150"></canvas>
    
    
    </body>
    
    </html>

     

    Now copy below written javascript function at the end of your html file.

    <script>
    
    
    function drawtriangle() {
      var triangle = document.getElementById('triangle');
      if (triangle.getContext){
        var ctx = triangle.getContext('2d');
    
        ctx.beginPath();
        ctx.moveTo(75,50);
        ctx.lineTo(100,75);
        ctx.lineTo(100,25);
        ctx.fill();
      }
    }
    
    
    function drawsquare() {
      var square = document.getElementById('square');
      if (square.getContext) {
        var ctx = square.getContext('2d');
    
        ctx.fillRect(25,25,100,100);
        ctx.clearRect(45,45,60,60);
        ctx.strokeRect(50,50,50,50);
      }
    }
    
    
    </script>

     

    Comment: Canvas element has no drawing ability, we have to use the script for drawing graphics. An Object will be returned by getContext() method which provides methods and properties for drawing on the canvas.

     

    Note: Internet Explorer 9, Firefox, Opera, Chrome, and Safari support <canvas> element and its properties. Internet Explorer 8 and earlier versions, do not support the <canvas> element.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: