Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Draw Rectangle in HTML Canvas

    • 0
    • 3
    • 3
    • 1
    • 0
    • 0
    • 0
    • 0
    • 387
    Comment on it

    Draw Rectangle in web page: We can now draw the graphics in web pages. Html provides the Canvas API for drawing graphics. Html5 has the <canvas> tag to draw the graphics using JavaScript. Using <canvas> element we can draw rectangle, line, circle, graphs or do real-time video processing or rendering.

    Syntax for creating canvas in HTML :

    <canvas id="canvs"></canvas> 
    

    Here I will show you how we can draw the rectangle in HTML using <canvas> tag.

    Rectangle in HTML5 Canvas : To draw a simple rectangle you can use 'rect()' function of JavaScript.

    rect(x, y, width, height);
    

    Where :

    x : The x-coordinate of the upper-left corner of the rectangle.

    y : The y-coordinate of the upper-left corner of the rectangle.

    width : The width of the rectangle.

    height : The height of the rectangle.

    Example of canvas rect():

    Draw_Rectangle.html

    <!DOCTYPE html>
    <html>
    <body>
    <canvas id="drawCanvas" width="250" height="250" style="border:2px solid #d3d3d3;"></canvas>
    
    <script language=javascript type=text/javascript>
    var c = document.getElementById("drawCanvas");
    var ctx = c.getContext("2d");
    ctx.lineWidth="10";              // for border width
    ctx.strokeStyle="blue";         // for border color
    ctx.rect(30, 30, 100, 100);    // draw rectangle
    ctx.stroke();
    </script> 
    </body>
    </html>
    

    The above code will draw a blank rectangle with white background.

    If you want to create a filled rectangle with some color on background, then you can use fillRect() function.

    Example of filled rectangle :

    <script language=javascript type=text/javascript>
    var c = document.getElementById("drawCanvas");
    var ctx = c.getContext("2d");
    ctx.lineWidth="10";              // for border width
    ctx.strokeStyle="blue";         // for border color
    ctx.fillStyle = "green";    // background color of rectangle
    ctx.fillRect (30, 30, 100, 100);    // draw rectangle
    ctx.stroke();
    </script> 
    

 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: