Draw Circle and Square Javascript

Cartoon shapes with canvas

  • « Previous
  • Next »

Now that we take ready our canvas environment, we can get into the details of how to depict on the canvas. Past the finish of this article, you lot will accept learned how to draw rectangles, triangles, lines, arcs and curves, providing familiarity with some of the bones shapes. Working with paths is essential when drawing objects onto the sail and we will meet how that tin can exist done.

The filigree

Before nosotros tin can outset drawing, we need to talk near the sail grid or coordinate space. Our HTML skeleton from the previous page had a canvas chemical element 150 pixels wide and 150 pixels high.

Unremarkably ane unit of measurement in the grid corresponds to i pixel on the sail. The origin of this grid is positioned in the top left corner at coordinate (0,0). All elements are placed relative to this origin. And so the position of the height left corner of the bluish square becomes x pixels from the left and y pixels from the top, at coordinate (x,y). Subsequently in this tutorial we'll run across how we can translate the origin to a different position, rotate the filigree and even scale information technology, but for now we'll stick to the default.

Drawing rectangles

Different SVG, <canvass> merely supports two primitive shapes: rectangles and paths (lists of points connected by lines). All other shapes must be created by combining one or more than paths. Luckily, we have an assortment of path cartoon functions which make it possible to compose very circuitous shapes.

First allow's expect at the rectangle. There are three functions that draw rectangles on the canvas:

fillRect(x, y, width, height)

Draws a filled rectangle.

strokeRect(10, y, width, height)

Draws a rectangular outline.

clearRect(x, y, width, height)

Clears the specified rectangular area, making it fully transparent.

Each of these three functions takes the same parameters. ten and y specify the position on the sheet (relative to the origin) of the top-left corner of the rectangle. width and superlative provide the rectangle'due south size.

Below is the describe() role from the previous page, merely now it is making use of these three functions.

Rectangular shape example

                                  role                  draw                  (                  )                  {                  var                  canvas                  =                  document.                  getElementById                  (                  'canvas'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  canvass.                  getContext                  (                  'second'                  )                  ;                  ctx.                  fillRect                  (                  25                  ,                  25                  ,                  100                  ,                  100                  )                  ;                  ctx.                  clearRect                  (                  45                  ,                  45                  ,                  60                  ,                  60                  )                  ;                  ctx.                  strokeRect                  (                  50                  ,                  50                  ,                  50                  ,                  50                  )                  ;                  }                  }                              

This instance's output is shown beneath.

The fillRect() part draws a big black foursquare 100 pixels on each side. The clearRect() part so erases a 60x60 pixel square from the center, and then strokeRect() is chosen to create a rectangular outline 50x50 pixels inside the cleared square.

In upcoming pages we'll encounter ii alternative methods for clearRect(), and we'll also see how to alter the color and stroke style of the rendered shapes.

Unlike the path functions we'll come across in the next department, all three rectangle functions draw immediately to the sheet.

Drawing paths

Now let's look at paths. A path is a listing of points, connected by segments of lines that tin exist of different shapes, curved or not, of different width and of different color. A path, or even a subpath, can be closed. To brand shapes using paths, we take some extra steps:

  1. Showtime, you create the path.
  2. Then you use drawing commands to draw into the path.
  3. One time the path has been created, you tin can stroke or fill the path to render it.

Here are the functions used to perform these steps:

beginPath()

Creates a new path. One time created, hereafter drawing commands are directed into the path and used to build the path upwards.

Path methods

Methods to set up unlike paths for objects.

closePath()

Adds a straight line to the path, going to the start of the electric current sub-path.

stroke()

Draws the shape by stroking its outline.

fill()

Draws a solid shape by filling the path'south content area.

The first step to create a path is to call the beginPath(). Internally, paths are stored as a list of sub-paths (lines, arcs, etc) which together form a shape. Every time this method is called, the list is reset and we can start drawing new shapes.

Note: When the current path is empty, such every bit immediately after calling beginPath(), or on a newly created canvas, the beginning path construction command is always treated equally a moveTo(), regardless of what information technology actually is. For that reason, you lot will almost always want to specifically fix your starting position after resetting a path.

The second step is calling the methods that actually specify the paths to be drawn. We'll see these shortly.

The third, and an optional step, is to phone call closePath(). This method tries to close the shape past drawing a straight line from the current point to the outset. If the shape has already been closed or there's only i point in the list, this office does zero.

Note: When you telephone call fill up(), whatever open shapes are closed automatically, so yous don't take to call closePath(). This is not the case when you call stroke().

Drawing a triangle

For example, the code for drawing a triangle would await something like this:

                                  function                  draw                  (                  )                  {                  var                  canvas                  =                  document.                  getElementById                  (                  'canvas'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  canvas.                  getContext                  (                  'second'                  )                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  75                  ,                  50                  )                  ;                  ctx.                  lineTo                  (                  100                  ,                  75                  )                  ;                  ctx.                  lineTo                  (                  100                  ,                  25                  )                  ;                  ctx.                  fill up                  (                  )                  ;                  }                  }                              

The result looks like this:

Moving the pen

1 very useful part, which doesn't actually draw annihilation simply becomes part of the path listing described above, is the moveTo() part. You tin can probably best recollect of this as lifting a pen or pencil from ane spot on a piece of paper and placing it on the next.

moveTo(x, y)

Moves the pen to the coordinates specified by 10 and y.

When the sheet is initialized or beginPath() is called, you typically volition want to use the moveTo() function to place the starting bespeak somewhere else. Nosotros could as well use moveTo() to draw unconnected paths. Have a look at the smiley face below.

To try this for yourself, yous can utilise the code snippet beneath. Just paste information technology into the draw() role nosotros saw earlier.

                                  function                  depict                  (                  )                  {                  var                  canvas                  =                  document.                  getElementById                  (                  'sheet'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  canvas.                  getContext                  (                  '2d'                  )                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  arc                  (                  75                  ,                  75                  ,                  l                  ,                  0                  ,                  Math.                  PI                  *                  ii                  ,                  true                  )                  ;                  // Outer circle                  ctx.                  moveTo                  (                  110                  ,                  75                  )                  ;                  ctx.                  arc                  (                  75                  ,                  75                  ,                  35                  ,                  0                  ,                  Math.                  PI                  ,                  false                  )                  ;                  // Oral cavity (clockwise)                  ctx.                  moveTo                  (                  65                  ,                  65                  )                  ;                  ctx.                  arc                  (                  60                  ,                  65                  ,                  5                  ,                  0                  ,                  Math.                  PI                  *                  2                  ,                  truthful                  )                  ;                  // Left eye                  ctx.                  moveTo                  (                  95                  ,                  65                  )                  ;                  ctx.                  arc                  (                  90                  ,                  65                  ,                  5                  ,                  0                  ,                  Math.                  PI                  *                  2                  ,                  true                  )                  ;                  // Right heart                  ctx.                  stroke                  (                  )                  ;                  }                  }                              

The issue looks similar this:

If y'all'd like to run across the connecting lines, you lot can remove the lines that call moveTo().

Annotation: To larn more about the arc() part, meet the Arcs section below.

Lines

For drawing direct lines, employ the lineTo() method.

lineTo(x, y)

Draws a line from the current drawing position to the position specified by 10 and y.

This method takes two arguments, x and y, which are the coordinates of the line'south end indicate. The starting point is dependent on previously drawn paths, where the stop point of the previous path is the starting point for the post-obit, etc. The starting point tin can also be changed by using the moveTo() method.

The example below draws 2 triangles, one filled and i outlined.

                                  part                  draw                  (                  )                  {                  var                  canvas                  =                  document.                  getElementById                  (                  'canvas'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  canvas.                  getContext                  (                  '2d'                  )                  ;                  // Filled triangle                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  25                  ,                  25                  )                  ;                  ctx.                  lineTo                  (                  105                  ,                  25                  )                  ;                  ctx.                  lineTo                  (                  25                  ,                  105                  )                  ;                  ctx.                  make full                  (                  )                  ;                  // Stroked triangle                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  125                  ,                  125                  )                  ;                  ctx.                  lineTo                  (                  125                  ,                  45                  )                  ;                  ctx.                  lineTo                  (                  45                  ,                  125                  )                  ;                  ctx.                  closePath                  (                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  }                  }                              

This starts by calling beginPath() to start a new shape path. We and so use the moveTo() method to move the starting point to the desired position. Below this, two lines are fatigued which make up two sides of the triangle.

You'll detect the deviation between the filled and stroked triangle. This is, as mentioned above, because shapes are automatically closed when a path is filled, but not when they are stroked. If nosotros left out the closePath() for the stroked triangle, only two lines would have been drawn, not a complete triangle.

Arcs

To draw arcs or circles, we utilise the arc() or arcTo() methods.

arc(ten, y, radius, startAngle, endAngle, counterclockwise)

Draws an arc which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction indicated past counterclockwise (defaulting to clockwise).

arcTo(x1, y1, x2, y2, radius)

Draws an arc with the given control points and radius, connected to the previous signal past a direct line.

Permit's accept a more detailed wait at the arc method, which takes six parameters: 10 and y are the coordinates of the middle of the circle on which the arc should be fatigued. radius is self-explanatory. The startAngle and endAngle parameters define the outset and end points of the arc in radians, along the bend of the circle. These are measured from the x axis. The counterclockwise parameter is a Boolean value which, when true, draws the arc counterclockwise; otherwise, the arc is drawn clockwise.

Note: Angles in the arc function are measured in radians, not degrees. To convert degrees to radians you tin can apply the following JavaScript expression: radians = (Math.PI/180)*degrees.

The following example is a little more complex than the ones we've seen higher up. It draws 12 different arcs all with unlike angles and fills.

The 2 for loops are for looping through the rows and columns of arcs. For each arc, we start a new path by calling beginPath(). In the lawmaking, each of the parameters for the arc is in a variable for clarity, merely yous wouldn't necessarily practise that in real life.

The x and y coordinates should be clear plenty. radius and startAngle are stock-still. The endAngle starts at 180 degrees (half a circle) in the offset column and is increased by steps of 90 degrees, culminating in a complete circle in the last column.

The argument for the clockwise parameter results in the first and third row being fatigued every bit clockwise arcs and the second and quaternary row as counterclockwise arcs. Finally, the if statement makes the acme one-half stroked arcs and the bottom one-half filled arcs.

Annotation: This case requires a slightly larger canvass than the others on this folio: 150 ten 200 pixels.

                                  function                  draw                  (                  )                  {                  var                  sail                  =                  document.                  getElementById                  (                  'canvas'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  sail.                  getContext                  (                  '2d'                  )                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  4                  ;                  i++                  )                  {                  for                  (                  var                  j                  =                  0                  ;                  j                  <                  3                  ;                  j++                  )                  {                  ctx.                  beginPath                  (                  )                  ;                  var                  x                  =                  25                  +                  j                  *                  50                  ;                  // 10 coordinate                  var                  y                  =                  25                  +                  i                  *                  fifty                  ;                  // y coordinate                  var                  radius                  =                  xx                  ;                  // Arc radius                  var                  startAngle                  =                  0                  ;                  // Starting bespeak on circle                  var                  endAngle                  =                  Math.                  PI                  +                  (Math.                  PI                  *                  j)                  /                  2                  ;                  // Finish point on circumvolve                  var                  counterclockwise                  =                  i                  %                  two                  !==                  0                  ;                  // clockwise or counterclockwise                  ctx.                  arc                  (x,                  y,                  radius,                  startAngle,                  endAngle,                  counterclockwise)                  ;                  if                  (i                  >                  one                  )                  {                  ctx.                  fill                  (                  )                  ;                  }                  else                  {                  ctx.                  stroke                  (                  )                  ;                  }                  }                  }                  }                  }                              

Bezier and quadratic curves

The next blazon of paths available are Bézier curves, bachelor in both cubic and quadratic varieties. These are mostly used to draw complex organic shapes.

quadraticCurveTo(cp1x, cp1y, x, y)

Draws a quadratic Bézier curve from the current pen position to the end point specified by x and y, using the command bespeak specified past cp1x and cp1y.

bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Draws a cubic Bézier curve from the electric current pen position to the end betoken specified by x and y, using the command points specified by (cp1x, cp1y) and (cp2x, cp2y).

The departure between these is that a quadratic Bézier curve has a kickoff and an end point (blueish dots) and just one control bespeak (indicated by the red dot) while a cubic Bézier curve uses ii control points.

The x and y parameters in both of these methods are the coordinates of the terminate point. cp1x and cp1y are the coordinates of the start command indicate, and cp2x and cp2y are the coordinates of the second control signal.

Using quadratic and cubic Bézier curves can be quite challenging, because unlike vector drawing software like Adobe Illustrator, we don't have direct visual feedback as to what nosotros're doing. This makes information technology pretty hard to depict circuitous shapes. In the following case, nosotros'll be drawing some simple organic shapes, just if you have the time and, most of all, the patience, much more complex shapes can exist created.

There'southward naught very hard in these examples. In both cases we see a succession of curves beingness fatigued which finally result in a complete shape.

Quadratic Bezier curves

This case uses multiple quadratic Bézier curves to render a speech balloon.

                                  function                  depict                  (                  )                  {                  var                  canvass                  =                  document.                  getElementById                  (                  'canvas'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  canvas.                  getContext                  (                  '2nd'                  )                  ;                  // Quadratic curves example                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  75                  ,                  25                  )                  ;                  ctx.                  quadraticCurveTo                  (                  25                  ,                  25                  ,                  25                  ,                  62.five                  )                  ;                  ctx.                  quadraticCurveTo                  (                  25                  ,                  100                  ,                  50                  ,                  100                  )                  ;                  ctx.                  quadraticCurveTo                  (                  fifty                  ,                  120                  ,                  30                  ,                  125                  )                  ;                  ctx.                  quadraticCurveTo                  (                  60                  ,                  120                  ,                  65                  ,                  100                  )                  ;                  ctx.                  quadraticCurveTo                  (                  125                  ,                  100                  ,                  125                  ,                  62.five                  )                  ;                  ctx.                  quadraticCurveTo                  (                  125                  ,                  25                  ,                  75                  ,                  25                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  }                  }                              

Cubic Bezier curves

This example draws a heart using cubic Bézier curves.

                                  function                  draw                  (                  )                  {                  var                  canvas                  =                  document.                  getElementById                  (                  'canvass'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  sheet.                  getContext                  (                  '2d'                  )                  ;                  // Cubic curves example                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  75                  ,                  twoscore                  )                  ;                  ctx.                  bezierCurveTo                  (                  75                  ,                  37                  ,                  seventy                  ,                  25                  ,                  50                  ,                  25                  )                  ;                  ctx.                  bezierCurveTo                  (                  twenty                  ,                  25                  ,                  xx                  ,                  62.five                  ,                  twenty                  ,                  62.5                  )                  ;                  ctx.                  bezierCurveTo                  (                  20                  ,                  fourscore                  ,                  xl                  ,                  102                  ,                  75                  ,                  120                  )                  ;                  ctx.                  bezierCurveTo                  (                  110                  ,                  102                  ,                  130                  ,                  eighty                  ,                  130                  ,                  62.five                  )                  ;                  ctx.                  bezierCurveTo                  (                  130                  ,                  62.5                  ,                  130                  ,                  25                  ,                  100                  ,                  25                  )                  ;                  ctx.                  bezierCurveTo                  (                  85                  ,                  25                  ,                  75                  ,                  37                  ,                  75                  ,                  40                  )                  ;                  ctx.                  fill                  (                  )                  ;                  }                  }                              

Rectangles

In addition to the three methods nosotros saw in Cartoon rectangles, which draw rectangular shapes directly to the canvas, there's too the rect() method, which adds a rectangular path to a currently open up path.

rect(x, y, width, height)

Draws a rectangle whose superlative-left corner is specified by (x, y) with the specified width and height.

Earlier this method is executed, the moveTo() method is automatically chosen with the parameters (ten,y). In other words, the electric current pen position is automatically reset to the default coordinates.

Making combinations

So far, each case on this page has used merely one type of path function per shape. However, there's no limitation to the number or types of paths you can use to create a shape. Then in this terminal example, let's combine all of the path functions to make a set of very famous game characters.

                                  function                  draw                  (                  )                  {                  var                  canvas                  =                  document.                  getElementById                  (                  'canvas'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  canvass.                  getContext                  (                  '2d'                  )                  ;                  roundedRect                  (ctx,                  12                  ,                  12                  ,                  150                  ,                  150                  ,                  15                  )                  ;                  roundedRect                  (ctx,                  19                  ,                  xix                  ,                  150                  ,                  150                  ,                  9                  )                  ;                  roundedRect                  (ctx,                  53                  ,                  53                  ,                  49                  ,                  33                  ,                  10                  )                  ;                  roundedRect                  (ctx,                  53                  ,                  119                  ,                  49                  ,                  16                  ,                  6                  )                  ;                  roundedRect                  (ctx,                  135                  ,                  53                  ,                  49                  ,                  33                  ,                  10                  )                  ;                  roundedRect                  (ctx,                  135                  ,                  119                  ,                  25                  ,                  49                  ,                  ten                  )                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  arc                  (                  37                  ,                  37                  ,                  13                  ,                  Math.                  PI                  /                  seven                  ,                  -Math.                  PI                  /                  7                  ,                  false                  )                  ;                  ctx.                  lineTo                  (                  31                  ,                  37                  )                  ;                  ctx.                  fill                  (                  )                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  eight                  ;                  i++                  )                  {                  ctx.                  fillRect                  (                  51                  +                  i                  *                  16                  ,                  35                  ,                  four                  ,                  four                  )                  ;                  }                  for                  (i                  =                  0                  ;                  i                  <                  6                  ;                  i++                  )                  {                  ctx.                  fillRect                  (                  115                  ,                  51                  +                  i                  *                  xvi                  ,                  four                  ,                  4                  )                  ;                  }                  for                  (i                  =                  0                  ;                  i                  <                  8                  ;                  i++                  )                  {                  ctx.                  fillRect                  (                  51                  +                  i                  *                  16                  ,                  99                  ,                  iv                  ,                  4                  )                  ;                  }                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  83                  ,                  116                  )                  ;                  ctx.                  lineTo                  (                  83                  ,                  102                  )                  ;                  ctx.                  bezierCurveTo                  (                  83                  ,                  94                  ,                  89                  ,                  88                  ,                  97                  ,                  88                  )                  ;                  ctx.                  bezierCurveTo                  (                  105                  ,                  88                  ,                  111                  ,                  94                  ,                  111                  ,                  102                  )                  ;                  ctx.                  lineTo                  (                  111                  ,                  116                  )                  ;                  ctx.                  lineTo                  (                  106.333                  ,                  111.333                  )                  ;                  ctx.                  lineTo                  (                  101.666                  ,                  116                  )                  ;                  ctx.                  lineTo                  (                  97                  ,                  111.333                  )                  ;                  ctx.                  lineTo                  (                  92.333                  ,                  116                  )                  ;                  ctx.                  lineTo                  (                  87.666                  ,                  111.333                  )                  ;                  ctx.                  lineTo                  (                  83                  ,                  116                  )                  ;                  ctx.                  fill up                  (                  )                  ;                  ctx.fillStyle                  =                  'white'                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  91                  ,                  96                  )                  ;                  ctx.                  bezierCurveTo                  (                  88                  ,                  96                  ,                  87                  ,                  99                  ,                  87                  ,                  101                  )                  ;                  ctx.                  bezierCurveTo                  (                  87                  ,                  103                  ,                  88                  ,                  106                  ,                  91                  ,                  106                  )                  ;                  ctx.                  bezierCurveTo                  (                  94                  ,                  106                  ,                  95                  ,                  103                  ,                  95                  ,                  101                  )                  ;                  ctx.                  bezierCurveTo                  (                  95                  ,                  99                  ,                  94                  ,                  96                  ,                  91                  ,                  96                  )                  ;                  ctx.                  moveTo                  (                  103                  ,                  96                  )                  ;                  ctx.                  bezierCurveTo                  (                  100                  ,                  96                  ,                  99                  ,                  99                  ,                  99                  ,                  101                  )                  ;                  ctx.                  bezierCurveTo                  (                  99                  ,                  103                  ,                  100                  ,                  106                  ,                  103                  ,                  106                  )                  ;                  ctx.                  bezierCurveTo                  (                  106                  ,                  106                  ,                  107                  ,                  103                  ,                  107                  ,                  101                  )                  ;                  ctx.                  bezierCurveTo                  (                  107                  ,                  99                  ,                  106                  ,                  96                  ,                  103                  ,                  96                  )                  ;                  ctx.                  fill                  (                  )                  ;                  ctx.fillStyle                  =                  'black'                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  arc                  (                  101                  ,                  102                  ,                  two                  ,                  0                  ,                  Math.                  PI                  *                  2                  ,                  truthful                  )                  ;                  ctx.                  fill                  (                  )                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  arc                  (                  89                  ,                  102                  ,                  2                  ,                  0                  ,                  Math.                  PI                  *                  2                  ,                  true                  )                  ;                  ctx.                  fill up                  (                  )                  ;                  }                  }                  // A utility part to draw a rectangle with rounded corners.                  function                  roundedRect                  (                  ctx,                    10,                    y,                    width,                    height,                    radius                  )                  {                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (x,                  y                  +                  radius)                  ;                  ctx.                  arcTo                  (x,                  y                  +                  tiptop,                  10                  +                  radius,                  y                  +                  height,                  radius)                  ;                  ctx.                  arcTo                  (x                  +                  width,                  y                  +                  meridian,                  x                  +                  width,                  y                  +                  acme                  -                  radius,                  radius)                  ;                  ctx.                  arcTo                  (x                  +                  width,                  y,                  x                  +                  width                  -                  radius,                  y,                  radius)                  ;                  ctx.                  arcTo                  (ten,                  y,                  10,                  y                  +                  radius,                  radius)                  ;                  ctx.                  stroke                  (                  )                  ;                  }                              

The resulting image looks similar this:

We won't get over this in particular, since information technology'south really surprisingly simple. The most important things to note are the use of the fillStyle property on the drawing context, and the apply of a utility function (in this case roundedRect()). Using utility functions for bits of drawing you do ofttimes can be very helpful and reduce the corporeality of lawmaking you demand, too as its complication.

We'll accept another await at fillStyle, in more detail, later in this tutorial. Here, all nosotros're doing is using information technology to change the fill color for paths from the default colour of black to white, and then back again.

Path2D objects

As we have seen in the final example, there can be a serial of paths and drawing commands to describe objects onto your sheet. To simplify the lawmaking and to improve operation, the Path2D object, available in recent versions of browsers, lets you cache or tape these drawing commands. You are able to play back your paths rapidly. Let's see how we tin construct a Path2D object:

Path2D()

The Path2D() constructor returns a newly instantiated Path2D object, optionally with another path as an argument (creates a copy), or optionally with a cord consisting of SVG path data.

                                  new                  Path2D                  (                  )                  ;                  // empty path object                  new                  Path2D                  (path)                  ;                  // copy from another Path2D object                  new                  Path2D                  (d)                  ;                  // path from SVG path data                              

All path methods similar moveTo, rect, arc or quadraticCurveTo, etc., which we got to know above, are available on Path2D objects.

The Path2D API also adds a mode to combine paths using the addPath method. This can be useful when you desire to build objects from several components, for case.

Path2D.addPath(path [, transform])

Adds a path to the current path with an optional transformation matrix.

Path2D case

In this instance, nosotros are creating a rectangle and a circle. Both are stored as a Path2D object, so that they are bachelor for later on usage. With the new Path2D API, several methods got updated to optionally accept a Path2D object to utilize instead of the current path. Hither, stroke and fill are used with a path argument to draw both objects onto the sail, for example.

                                  function                  draw                  (                  )                  {                  var                  canvass                  =                  certificate.                  getElementById                  (                  'sheet'                  )                  ;                  if                  (canvas.getContext)                  {                  var                  ctx                  =                  canvas.                  getContext                  (                  '2d'                  )                  ;                  var                  rectangle                  =                  new                  Path2D                  (                  )                  ;                  rectangle.                  rect                  (                  10                  ,                  10                  ,                  50                  ,                  50                  )                  ;                  var                  circle                  =                  new                  Path2D                  (                  )                  ;                  circle.                  arc                  (                  100                  ,                  35                  ,                  25                  ,                  0                  ,                  ii                  *                  Math.                  PI                  )                  ;                  ctx.                  stroke                  (rectangle)                  ;                  ctx.                  fill                  (circle)                  ;                  }                  }                              

Using SVG paths

Another powerful characteristic of the new canvas Path2D API is using SVG path data to initialize paths on your sheet. This might allow you lot to pass around path information and re-use them in both, SVG and canvas.

The path volition motility to indicate (M10 x) and then motility horizontally 80 points to the correct (h lxxx), then 80 points down (five 80), then 80 points to the left (h -eighty), and then dorsum to the start (z). You can see this example on the Path2D constructor page.

                                  var                  p                  =                  new                  Path2D                  (                  'M10 x h fourscore v eighty h -80 Z'                  )                  ;                              
  • « Previous
  • Next »

bauermostases.blogspot.com

Source: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes

0 Response to "Draw Circle and Square Javascript"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel