官术网_书友最值得收藏!

  • Canvas Cookbook
  • Bhushan Purushottam Joshi
  • 235字
  • 2021-07-16 11:03:16

Drawing rectangles

There are three different functions in the canvas API to draw rectangles. They are:

  • rect(xPos,yPos,width,height)
  • fillRect(xPos,yPos,width,height)
  • strokeRect(xPos,yPos,width,height)

Let's see these all together in a single recipe. So here is the output of our first recipe:

Drawing rectangles

How to do it…

The output that shows three different rectangles, uses a call to three different functions, which are explained further. The recipe is as follows.

An HTML file that includes the canvas element:

<html>
<head>
<title>Rectangles</title>
<script src="Rectangles.js"></script>
</head>
<body onload="init()" bgcolor="#FFFFCC">
<canvas id="canvas" width="250" height="200" style="border:2px solid blue;" >
  your browser does not support canvas
</canvas>
<H1>Rectangles</H1>
</body>
</html>

The JavaScript file as mentioned in the <script> tag in the previously given code:

function init()
{
  var canvas = document.getElementById("canvas");
  if(canvas.getContext)
  {
    // Color of drawing, fillStyle is this color
    var ctx = canvas.getContext("2d");    

    // Draw a square(rectangle with same sides)
    // from top left corner x,y, width, height
    ctx.strokeStyle="purple"  
    ctx.rect(10,10,70,50);
    ctx.fillStyle="lightgreen";
    ctx.fill();
    ctx.stroke();  

    //draw another rectangle
    ctx.fillStyle="crimson";
    ctx.fillRect (50,25, 100,100);

    //draw yet another
    ctx.strokeStyle="blue";  
    ctx.lineWidth=10;  
    ctx.strokeRect(100,60,80,130);    
  }
}

How it works...

This is what you can observe in the output of the recipe:

  • The top-most blue bordered rectangle is drawn using the strokeRect() function
  • The second red colored rectangle is drawn using the fillRect() function
  • The first green colored rectangle is drawn using the rect() and fill() functions

The property fillStyle decides the color for filling the rectangle. The strokeStyle property decides the color of the border.

The three rectangles drawing functions accept the following parameters:

Diagrammatically it can be shown as follows:

How it works...
主站蜘蛛池模板: 青田县| 宝应县| 兴化市| 鲁甸县| 通榆县| 彩票| 甘肃省| 融水| 深水埗区| 天津市| 台北县| 乃东县| 莱州市| 天台县| 科技| 甘洛县| 连云港市| 石棉县| 高邮市| 镇雄县| 栾川县| 青龙| 广宗县| 桐庐县| 黎城县| 安阳县| 团风县| 凤凰县| 海淀区| 梨树县| 长阳| 鄄城县| 贺州市| 永兴县| 莲花县| 称多县| 天等县| 抚州市| 故城县| 上犹县| 博湖县|