HTML Canvas Rectangle

Introduction

We can draw a simple rectangle by using the rect() method:

context.rect(x,y,width,height); 

The rect() method draws a rectangle at the position x,y, with width and height.

We can assign a fill color using the fillStyle method and fill the shape using fill().

View in separate window


<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                /*from  ww w  . j  av  a2 s . c  o  m*/
                context.rect(canvas.width / 2 - 100, canvas.height / 2 - 50, 200, 100);
                context.fillStyle = "#8ED6FF";
                context.fill();
                context.lineWidth = 5;
                context.strokeStyle = "black";
                context.stroke();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>



PreviousNext

Related