Draw rectangle with canvas

canvas is a new feature of HTML5, we can use it to draw a rectangle easily

code show as below:

    <!DOCTYPE html>  
    <html>  
    <head>  
    <meta charset="utf-8" />  
    <title>Draw rectangle with canvas</title>  
    <style>  
      
    </style>  
    </head>  
    <body>  
    <canvas id="canvas" width="600" height="400"></canvas>  
    <script type="text/javascript">  
      function draw(id){  
          var canvas = document.getElementById(id);  
          var context = canvas.getContext('2d'); //getContext() method returns an object  
          context.fillStyle = "blue"; // set or return the color, gradient or pattern used to fill the painting              
          context.fillRect(50,50,400,300); // x-axis and y-axis width and height, draw a "filled" rectangle  
            
     }  
     draw("canvas");  
    </script>  
    </body>  
    </html>  
The above code is a filled rectangle.

We can also use canvas to draw unfilled rectangles

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Draw rectangle with canvas</title>
<style>

</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script type="text/javascript">
  function draw(id){
      var canvas = document.getElementById(id);
      var context = canvas.getContext('2d'); //getContext() method returns an object
      context.strokeStyle = "#000"; //The fill color of the graphic border
      context.lineWidth = 5; // Draw a rectangle with a line width of 5 pixels:     
      context.strokeRect(50,50,180,120); //Draw a rectangle (no fill)
      context.strokeRect(110,110,180,120);      
 }
 draw("canvas");
</script>
</body>
</html>

Program running result:




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640249&siteId=291194637