Javascript required
Skip to content Skip to sidebar Skip to footer

Javascript Draw Square With Circle in Middle

Applying styles and colors

  • « Previous
  • Next »

In the chapter virtually drawing shapes, nosotros used only the default line and fill styles. Hither we will explore the sail options we take at our disposal to brand our drawings a little more attractive. You will learn how to add together dissimilar colors, line styles, gradients, patterns and shadows to your drawings.

Colors

Up until now we have simply seen methods of the cartoon context. If nosotros desire to utilise colors to a shape, there are 2 important properties we tin can use: fillStyle and strokeStyle.

fillStyle = color

Sets the fashion used when filling shapes.

strokeStyle = color

Sets the manner for shapes' outlines.

color is a string representing a CSS <color>, a gradient object, or a pattern object. Nosotros'll wait at slope and blueprint objects later. By default, the stroke and fill color are gear up to black (CSS color value #000000).

Notation: When you fix the strokeStyle and/or fillStyle property, the new value becomes the default for all shapes beingness drawn from and so on. For every shape y'all want in a different color, you will need to reassign the fillStyle or strokeStyle property.

The valid strings you tin enter should, according to the specification, be CSS <colour> values. Each of the following examples depict the same color.

                                  // these all set up the fillStyle to 'orange'                  ctx.fillStyle                  =                  'orangish'                  ;                  ctx.fillStyle                  =                  '#FFA500'                  ;                  ctx.fillStyle                  =                  'rgb(255, 165, 0)'                  ;                  ctx.fillStyle                  =                  'rgba(255, 165, 0, 1)'                  ;                              

A fillStyle instance

In this example, we once once more use two for loops to draw a filigree of rectangles, each in a unlike color. The resulting image should look something like the screenshot. There is naught too spectacular happening hither. Nosotros use the two variables i and j to generate a unique RGB color for each square, and only change the red and green values. The blue aqueduct has a fixed value. By modifying the channels, you can generate all kinds of palettes. By increasing the steps, y'all tin can achieve something that looks similar the color palettes Photoshop uses.

                                  function                  depict                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  'second'                  )                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  6                  ;                  i++                  )                  {                  for                  (                  var                  j                  =                  0                  ;                  j                  <                  6                  ;                  j++                  )                  {                  ctx.fillStyle                  =                  'rgb('                  +                  Math.                  flooring                  (                  255                  -                  42.5                  *                  i)                  +                  ', '                  +                  Math.                  floor                  (                  255                  -                  42.5                  *                  j)                  +                  ', 0)'                  ;                  ctx.                  fillRect                  (j                  *                  25                  ,                  i                  *                  25                  ,                  25                  ,                  25                  )                  ;                  }                  }                  }                              

The result looks like this:

A strokeStyle instance

This case is like to the one above, simply uses the strokeStyle property to modify the colors of the shapes' outlines. We use the arc() method to draw circles instead of squares.

                                  office                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvass'                  )                  .                  getContext                  (                  'second'                  )                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  six                  ;                  i++                  )                  {                  for                  (                  var                  j                  =                  0                  ;                  j                  <                  half dozen                  ;                  j++                  )                  {                  ctx.strokeStyle                  =                  'rgb(0, '                  +                  Math.                  flooring                  (                  255                  -                  42.v                  *                  i)                  +                  ', '                  +                  Math.                  floor                  (                  255                  -                  42.5                  *                  j)                  +                  ')'                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  arc                  (                  12.5                  +                  j                  *                  25                  ,                  12.v                  +                  i                  *                  25                  ,                  10                  ,                  0                  ,                  Math.                  PI                  *                  ii                  ,                  true                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  }                  }                  }                              

The result looks similar this:

Transparency

In add-on to drawing opaque shapes to the canvas, we can also draw semi-transparent (or translucent) shapes. This is washed past either setting the globalAlpha holding or by assigning a semi-transparent color to the stroke and/or fill up style.

globalAlpha = transparencyValue

Applies the specified transparency value to all hereafter shapes drawn on the canvas. The value must exist betwixt 0.0 (fully transparent) to ane.0 (fully opaque). This value is 1.0 (fully opaque) by default.

The globalAlpha property tin can exist useful if you want to draw a lot of shapes on the canvas with similar transparency, but otherwise information technology's more often than not more useful to gear up the transparency on individual shapes when setting their colors.

Considering the strokeStyle and fillStyle properties accept CSS rgba color values, nosotros tin utilise the following notation to assign a transparent color to them.

                                  // Assigning transparent colors to stroke and make full style                  ctx.strokeStyle                  =                  'rgba(255, 0, 0, 0.5)'                  ;                  ctx.fillStyle                  =                  'rgba(255, 0, 0, 0.5)'                  ;                              

The rgba() role is similar to the rgb() function merely it has one extra parameter. The last parameter sets the transparency value of this detail color. The valid range is again betwixt 0.0 (fully transparent) and i.0 (fully opaque).

A globalAlpha case

In this case, we'll depict a background of 4 unlike colored squares. On top of these, we'll describe a set up of semi-transparent circles. The globalAlpha property is set at 0.2 which volition be used for all shapes from that betoken on. Every step in the for loop draws a prepare of circles with an increasing radius. The terminal result is a radial gradient. By overlaying e'er more circles on summit of each other, nosotros effectively reduce the transparency of the circles that accept already been drawn. By increasing the stride count and in upshot drawing more than circles, the background would completely disappear from the heart of the image.

                                  part                  draw                  (                  )                  {                  var                  ctx                  =                  certificate.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  // describe groundwork                  ctx.fillStyle                  =                  '#FD0'                  ;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  75                  ,                  75                  )                  ;                  ctx.fillStyle                  =                  '#6C0'                  ;                  ctx.                  fillRect                  (                  75                  ,                  0                  ,                  75                  ,                  75                  )                  ;                  ctx.fillStyle                  =                  '#09F'                  ;                  ctx.                  fillRect                  (                  0                  ,                  75                  ,                  75                  ,                  75                  )                  ;                  ctx.fillStyle                  =                  '#F30'                  ;                  ctx.                  fillRect                  (                  75                  ,                  75                  ,                  75                  ,                  75                  )                  ;                  ctx.fillStyle                  =                  '#FFF'                  ;                  // set transparency value                  ctx.globalAlpha                  =                  0.2                  ;                  // Draw semi transparent circles                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  seven                  ;                  i++                  )                  {                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  arc                  (                  75                  ,                  75                  ,                  x                  +                  10                  *                  i,                  0                  ,                  Math.                  PI                  *                  2                  ,                  true                  )                  ;                  ctx.                  fill                  (                  )                  ;                  }                  }                              

An case using rgba()

In this 2nd case, we do something similar to the one above, but instead of drawing circles on top of each other, I've drawn small rectangles with increasing opacity. Using rgba() gives you a little more than command and flexibility because nosotros can gear up the fill and stroke style individually.

                                  function                  depict                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  // Depict groundwork                  ctx.fillStyle                  =                  'rgb(255, 221, 0)'                  ;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  150                  ,                  37.five                  )                  ;                  ctx.fillStyle                  =                  'rgb(102, 204, 0)'                  ;                  ctx.                  fillRect                  (                  0                  ,                  37.5                  ,                  150                  ,                  37.5                  )                  ;                  ctx.fillStyle                  =                  'rgb(0, 153, 255)'                  ;                  ctx.                  fillRect                  (                  0                  ,                  75                  ,                  150                  ,                  37.5                  )                  ;                  ctx.fillStyle                  =                  'rgb(255, 51, 0)'                  ;                  ctx.                  fillRect                  (                  0                  ,                  112.v                  ,                  150                  ,                  37.v                  )                  ;                  // Draw semi transparent rectangles                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  ten                  ;                  i++                  )                  {                  ctx.fillStyle                  =                  'rgba(255, 255, 255, '                  +                  (i                  +                  1                  )                  /                  10                  +                  ')'                  ;                  for                  (                  var                  j                  =                  0                  ;                  j                  <                  4                  ;                  j++                  )                  {                  ctx.                  fillRect                  (                  5                  +                  i                  *                  14                  ,                  5                  +                  j                  *                  37.5                  ,                  xiv                  ,                  27.five                  )                  ;                  }                  }                  }                              

Line styles

In that location are several backdrop which allow us to style lines.

lineWidth = value

Sets the width of lines drawn in the future.

lineCap = type

Sets the advent of the ends of lines.

lineJoin = type

Sets the appearance of the "corners" where lines come across.

miterLimit = value

Establishes a limit on the miter when two lines join at a sharp angle, to let yous control how thick the junction becomes.

getLineDash()

Returns the current line dash blueprint array containing an fifty-fifty number of not-negative numbers.

setLineDash(segments)

Sets the current line dash pattern.

lineDashOffset = value

Specifies where to start a nuance assortment on a line.

You'll get a better agreement of what these do by looking at the examples below.

A lineWidth case

This property sets the current line thickness. Values must be positive numbers. By default this value is prepare to 1.0 units.

The line width is the thickness of the stroke centered on the given path. In other words, the surface area that's fatigued extends to one-half the line width on either side of the path. Considering sheet coordinates practise not direct reference pixels, special care must exist taken to obtain crisp horizontal and vertical lines.

In the case below, x straight lines are fatigued with increasing line widths. The line on the far left is i.0 units wide. However, the leftmost and all other odd-integer-width thickness lines practise not appear well-baked, considering of the path's positioning.

                                  office                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  10                  ;                  i++                  )                  {                  ctx.lineWidth                  =                  1                  +                  i;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  5                  +                  i                  *                  14                  ,                  five                  )                  ;                  ctx.                  lineTo                  (                  5                  +                  i                  *                  fourteen                  ,                  140                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  }                  }                              

Obtaining crisp lines requires agreement how paths are stroked. In the images below, the grid represents the canvas coordinate filigree. The squares between gridlines are bodily on-screen pixels. In the get-go grid image beneath, a rectangle from (ii,1) to (v,5) is filled. The entire area between them (low-cal red) falls on pixel boundaries, and then the resulting filled rectangle volition accept well-baked edges.

If you consider a path from (iii,1) to (three,5) with a line thickness of 1.0, you end up with the situation in the second paradigm. The bodily area to exist filled (dark bluish) merely extends halfway into the pixels on either side of the path. An approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blueish and dark blueish) being filled in with a color just half as dark as the actual stroke color. This is what happens with the 1.0 width line in the previous example code.

To set this, you have to be very precise in your path creation. Knowing that a 1.0 width line volition extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,v) results in the state of affairs in the third paradigm—the ane.0 line width ends up completely and precisely filling a single pixel vertical line.

Note: Exist aware that in our vertical line example, the Y position still referenced an integer gridline position—if it hadn't, we would see pixels with half coverage at the endpoints (but note likewise that this behavior depends on the current lineCap style whose default value is butt; yous may want to compute consistent strokes with half-pixel coordinates for odd-width lines, by setting the lineCap style to foursquare, so that the outer edge of the stroke around the endpoint will be automatically extended to cover the whole pixel exactly).

Note besides that just start and last endpoints of a path are affected: if a path is closed with closePath(), at that place's no get-go and final endpoint; instead, all endpoints in the path are connected to their attached previous and next segment using the current setting of the lineJoin mode, whose default value is miter, with the effect of automatically extending the outer borders of the connected segments to their intersection point, then that the rendered stroke will exactly embrace full pixels centered at each endpoint if those connected segments are horizontal and/or vertical. Come across the next two sections for demonstrations of these additional line styles.

For even-width lines, each one-half ends upwardly being an integer amount of pixels, and then you want a path that is between pixels (that is, (three,i) to (3,5)), instead of downwards the middle of pixels.

While slightly painful when initially working with scalable 2nd graphics, paying attention to the pixel filigree and the position of paths ensures that your drawings will look correct regardless of scaling or any other transformations involved. A i.0-width vertical line drawn at the correct position will become a crisp 2-pixel line when scaled up by 2, and will announced at the correct position.

A lineCap example

The lineCap holding determines how the end points of every line are drawn. There are 3 possible values for this holding and those are: butt, round and square. By default this property is set up to butt:

butt

The ends of lines are squared off at the endpoints.

round

The ends of lines are rounded.

foursquare

The ends of lines are squared off by calculation a box with an equal width and one-half the summit of the line's thickness.

In this example, we'll draw three lines, each with a different value for the lineCap holding. I also added ii guides to encounter the exact differences between the iii. Each of these lines starts and ends exactly on these guides.

The line on the left uses the default butt option. You'll observe that it'southward drawn completely affluent with the guides. The second is prepare to utilize the round option. This adds a semicircle to the stop that has a radius half the width of the line. The line on the right uses the square choice. This adds a box with an equal width and half the height of the line thickness.

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2nd'                  )                  ;                  var                  lineCap                  =                  [                  'butt'                  ,                  'round'                  ,                  'square'                  ]                  ;                  // Describe guides                  ctx.strokeStyle                  =                  '#09f'                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  x                  ,                  ten                  )                  ;                  ctx.                  lineTo                  (                  140                  ,                  10                  )                  ;                  ctx.                  moveTo                  (                  10                  ,                  140                  )                  ;                  ctx.                  lineTo                  (                  140                  ,                  140                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  // Draw lines                  ctx.strokeStyle                  =                  'black'                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  lineCap.length;                  i++                  )                  {                  ctx.lineWidth                  =                  xv                  ;                  ctx.lineCap                  =                  lineCap[i]                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  25                  +                  i                  *                  50                  ,                  10                  )                  ;                  ctx.                  lineTo                  (                  25                  +                  i                  *                  l                  ,                  140                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  }                  }                              

A lineJoin instance

The lineJoin belongings determines how ii connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together (degenerate segments with zero lengths, whose specified endpoints and control points are exactly at the same position, are skipped).

There are three possible values for this holding: round, bevel and miter. By default this belongings is set to miter. Note that the lineJoin setting has no effect if the two connected segments take the same direction, considering no joining area will exist added in this instance:

round

Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to half the line width.

bevel

Fills an additional triangular area between the mutual endpoint of connected segments, and the split outside rectangular corners of each segment.

miter

Connected segments are joined past extending their outside edges to connect at a single point, with the upshot of filling an additional lozenge-shaped area. This setting is effected by the miterLimit property which is explained below.

The instance below draws three unlike paths, demonstrating each of these three lineJoin belongings settings; the output is shown above.

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  var                  lineJoin                  =                  [                  'circular'                  ,                  'bevel'                  ,                  'miter'                  ]                  ;                  ctx.lineWidth                  =                  10                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  lineJoin.length;                  i++                  )                  {                  ctx.lineJoin                  =                  lineJoin[i]                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  -                  five                  ,                  5                  +                  i                  *                  forty                  )                  ;                  ctx.                  lineTo                  (                  35                  ,                  45                  +                  i                  *                  twoscore                  )                  ;                  ctx.                  lineTo                  (                  75                  ,                  v                  +                  i                  *                  40                  )                  ;                  ctx.                  lineTo                  (                  115                  ,                  45                  +                  i                  *                  40                  )                  ;                  ctx.                  lineTo                  (                  155                  ,                  5                  +                  i                  *                  40                  )                  ;                  ctx.                  stroke                  (                  )                  ;                  }                  }                              

A demo of the miterLimit belongings

As you've seen in the previous case, when joining two lines with the miter selection, the outside edges of the two joining lines are extended up to the point where they meet. For lines which are at big angles with each other, this point is not far from the inside connection betoken. However, equally the angles between each line decreases, the distance (miter length) between these points increases exponentially.

The miterLimit holding determines how far the outside connection point tin be placed from the within connection indicate. If ii lines exceed this value, a bevel bring together gets drawn instead. Note that the maximum miter length is the production of the line width measured in the current coordinate system, by the value of this miterLimit property (whose default value is 10.0 in the HTML <canvas>), so the miterLimit can be set independently from the current display calibration or whatever affine transforms of paths: it only influences the effectively rendered shape of line edges.

More than exactly, the miter limit is the maximum allowed ratio of the extension length (in the HTML canvas, it is measured between the outside corner of the joined edges of the line and the common endpoint of connecting segments specified in the path) to half the line width. It tin can equivalently exist defined as the maximum allowed ratio of the distance betwixt the inside and outside points of junction of edges, to the total line width. Information technology is then equal to the cosecant of half the minimum inner angle of connecting segments below which no miter join volition be rendered, but but a bevel bring together:

  • miterLimit = max miterLength / lineWidth = i / sin ( min θ / two )
  • The default miter limit of ten.0 will strip all miters for sharp angles below near 11 degrees.
  • A miter limit equal to √2 ≈ 1.4142136 (rounded upwardly) will strip miters for all astute angles, keeping miter joins but for obtuse or right angles.
  • A miter limit equal to 1.0 is valid simply volition disable all miters.
  • Values below i.0 are invalid for the miter limit.

Hither's a footling demo in which yous can set miterLimit dynamically and encounter how this furnishings the shapes on the canvas. The bluish lines show where the get-go and endpoints for each of the lines in the zig-zag design are.

If you specify a miterLimit value below iv.two in this demo, none of the visible corners volition join with a miter extension, simply only with a small bevel almost the blue lines; with a miterLimit above 10, most corners in this demo should join with a miter far away from the blueish lines, and whose height is decreasing between corners from left to right considering they connect with growing angles; with intermediate values, the corners on the left side will only join with a bevel nearly the blue lines, and the corners on the correct side with a miter extension (likewise with a decreasing height).

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  // Clear canvas                  ctx.                  clearRect                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  // Describe guides                  ctx.strokeStyle                  =                  '#09f'                  ;                  ctx.lineWidth                  =                  ii                  ;                  ctx.                  strokeRect                  (                  -                  five                  ,                  50                  ,                  160                  ,                  l                  )                  ;                  // Fix line styles                  ctx.strokeStyle                  =                  '#000'                  ;                  ctx.lineWidth                  =                  10                  ;                  // check input                  if                  (document.                  getElementById                  (                  'miterLimit'                  )                  .value.                  match                  (                                      /                    \d+(\.\d+)?                    /                                    )                  )                  {                  ctx.miterLimit                  =                  parseFloat                  (document.                  getElementById                  (                  'miterLimit'                  )                  .value)                  ;                  }                  else                  {                  alarm                  (                  'Value must exist a positive number'                  )                  ;                  }                  // Draw lines                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  moveTo                  (                  0                  ,                  100                  )                  ;                  for                  (i                  =                  0                  ;                  i                  <                  24                  ;                  i++                  )                  {                  var                  dy                  =                  i                  %                  two                  ==                  0                  ?                  25                  :                  -                  25                  ;                  ctx.                  lineTo                  (Math.                  pow                  (i,                  ane.5                  )                  *                  2                  ,                  75                  +                  dy)                  ;                  }                  ctx.                  stroke                  (                  )                  ;                  return                  false                  ;                  }                              

Using line dashes

The setLineDash method and the lineDashOffset property specify the dash pattern for lines. The setLineDash method accepts a list of numbers that specifies distances to alternately draw a line and a gap and the lineDashOffset property sets an offset where to kickoff the pattern.

In this example we are creating a marching ants effect. It is an animation technique frequently institute in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background past animating the edge. In a later on role of this tutorial, yous tin learn how to do this and other basic animations.

                                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  var                  offset                  =                  0                  ;                  function                  draw                  (                  )                  {                  ctx.                  clearRect                  (                  0                  ,                  0                  ,                  canvas.width,                  canvas.height)                  ;                  ctx.                  setLineDash                  (                  [                  4                  ,                  2                  ]                  )                  ;                  ctx.lineDashOffset                  =                  -showtime;                  ctx.                  strokeRect                  (                  10                  ,                  10                  ,                  100                  ,                  100                  )                  ;                  }                  function                  march                  (                  )                  {                  offset++                  ;                  if                  (offset                  >                  xvi                  )                  {                  offset                  =                  0                  ;                  }                  draw                  (                  )                  ;                  setTimeout                  (march,                  20                  )                  ;                  }                  march                  (                  )                  ;                              

Gradients

Simply like whatsoever normal drawing plan, we can fill up and stroke shapes using linear, radial and conic gradients. We create a CanvasGradient object past using one of the following methods. We tin then assign this object to the fillStyle or strokeStyle properties.

createLinearGradient(x1, y1, x2, y2)

Creates a linear slope object with a starting point of (x1, y1) and an end betoken of (x2, y2).

createRadialGradient(x1, y1, r1, x2, y2, r2)

Creates a radial gradient. The parameters represent two circles, one with its heart at (x1, y1) and a radius of r1, and the other with its center at (x2, y2) with a radius of r2.

createConicGradient(angle, x, y)

Creates a conic slope object with a starting angle of angle in radians, at the position (ten, y).

For example:

                                  var                  lineargradient                  =                  ctx.                  createLinearGradient                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  var                  radialgradient                  =                  ctx.                  createRadialGradient                  (                  75                  ,                  75                  ,                  0                  ,                  75                  ,                  75                  ,                  100                  )                  ;                              

Once we've created a CanvasGradient object we tin assign colors to it by using the addColorStop() method.

slope.addColorStop(position, colour)

Creates a new color end on the gradient object. The position is a number between 0.0 and 1.0 and defines the relative position of the color in the slope, and the color argument must be a cord representing a CSS <color>, indicating the color the gradient should accomplish at that offset into the transition.

Yous tin can add together every bit many colour stops to a slope as you need. Below is a very elementary linear gradient from white to black.

                                  var                  lineargradient                  =                  ctx.                  createLinearGradient                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  lineargradient.                  addColorStop                  (                  0                  ,                  'white'                  )                  ;                  lineargradient.                  addColorStop                  (                  1                  ,                  'black'                  )                  ;                              

A createLinearGradient example

In this example, nosotros'll create ii different gradients. As you tin see hither, both the strokeStyle and fillStyle properties can take a canvasGradient object as valid input.

                                  function                  depict                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2nd'                  )                  ;                  // Create gradients                  var                  lingrad                  =                  ctx.                  createLinearGradient                  (                  0                  ,                  0                  ,                  0                  ,                  150                  )                  ;                  lingrad.                  addColorStop                  (                  0                  ,                  '#00ABEB'                  )                  ;                  lingrad.                  addColorStop                  (                  0.5                  ,                  '#fff'                  )                  ;                  lingrad.                  addColorStop                  (                  0.5                  ,                  '#26C000'                  )                  ;                  lingrad.                  addColorStop                  (                  one                  ,                  '#fff'                  )                  ;                  var                  lingrad2                  =                  ctx.                  createLinearGradient                  (                  0                  ,                  fifty                  ,                  0                  ,                  95                  )                  ;                  lingrad2.                  addColorStop                  (                  0.five                  ,                  '#000'                  )                  ;                  lingrad2.                  addColorStop                  (                  1                  ,                  'rgba(0, 0, 0, 0)'                  )                  ;                  // assign gradients to fill and stroke styles                  ctx.fillStyle                  =                  lingrad;                  ctx.strokeStyle                  =                  lingrad2;                  // draw shapes                  ctx.                  fillRect                  (                  x                  ,                  ten                  ,                  130                  ,                  130                  )                  ;                  ctx.                  strokeRect                  (                  50                  ,                  fifty                  ,                  fifty                  ,                  50                  )                  ;                  }                              

The outset is a background gradient. As you tin encounter, nosotros assigned two colors at the same position. You practice this to brand very sharp color transitions—in this case from white to green. Ordinarily, it doesn't affair in what order y'all define the color stops, but in this special example, it does significantly. If you lot keep the assignments in the order you want them to appear, this won't exist a trouble.

In the second gradient, we didn't assign the starting color (at position 0.0) since it wasn't strictly necessary, considering it will automatically assume the color of the adjacent color terminate. Therefore, assigning the black color at position 0.5 automatically makes the gradient, from the start to this stop, blackness.

A createRadialGradient instance

In this example, we'll ascertain four dissimilar radial gradients. Because we accept control over the start and closing points of the gradient, nosotros tin accomplish more circuitous furnishings than we would normally have in the "classic" radial gradients we see in, for example, Photoshop (that is, a gradient with a single center signal where the gradient expands outward in a circular shape).

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  // Create gradients                  var                  radgrad                  =                  ctx.                  createRadialGradient                  (                  45                  ,                  45                  ,                  10                  ,                  52                  ,                  fifty                  ,                  thirty                  )                  ;                  radgrad.                  addColorStop                  (                  0                  ,                  '#A7D30C'                  )                  ;                  radgrad.                  addColorStop                  (                  0.ix                  ,                  '#019F62'                  )                  ;                  radgrad.                  addColorStop                  (                  1                  ,                  'rgba(1, 159, 98, 0)'                  )                  ;                  var                  radgrad2                  =                  ctx.                  createRadialGradient                  (                  105                  ,                  105                  ,                  xx                  ,                  112                  ,                  120                  ,                  50                  )                  ;                  radgrad2.                  addColorStop                  (                  0                  ,                  '#FF5F98'                  )                  ;                  radgrad2.                  addColorStop                  (                  0.75                  ,                  '#FF0188'                  )                  ;                  radgrad2.                  addColorStop                  (                  i                  ,                  'rgba(255, one, 136, 0)'                  )                  ;                  var                  radgrad3                  =                  ctx.                  createRadialGradient                  (                  95                  ,                  xv                  ,                  15                  ,                  102                  ,                  20                  ,                  40                  )                  ;                  radgrad3.                  addColorStop                  (                  0                  ,                  '#00C9FF'                  )                  ;                  radgrad3.                  addColorStop                  (                  0.8                  ,                  '#00B5E2'                  )                  ;                  radgrad3.                  addColorStop                  (                  1                  ,                  'rgba(0, 201, 255, 0)'                  )                  ;                  var                  radgrad4                  =                  ctx.                  createRadialGradient                  (                  0                  ,                  150                  ,                  50                  ,                  0                  ,                  140                  ,                  90                  )                  ;                  radgrad4.                  addColorStop                  (                  0                  ,                  '#F4F201'                  )                  ;                  radgrad4.                  addColorStop                  (                  0.8                  ,                  '#E4C700'                  )                  ;                  radgrad4.                  addColorStop                  (                  1                  ,                  'rgba(228, 199, 0, 0)'                  )                  ;                  // draw shapes                  ctx.fillStyle                  =                  radgrad4;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  ctx.fillStyle                  =                  radgrad3;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  ctx.fillStyle                  =                  radgrad2;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  ctx.fillStyle                  =                  radgrad;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  }                              

In this case, we've offset the starting point slightly from the end point to achieve a spherical 3D effect. It'southward best to try to avoid letting the inside and outside circles overlap because this results in foreign effects which are hard to predict.

The final color terminate in each of the 4 gradients uses a fully transparent color. If yous want to accept a nice transition from this to the previous colour stop, both colors should be equal. This isn't very obvious from the code because it uses two different CSS colour methods as a demonstration, but in the first gradient #019F62 = rgba(1,159,98,one).

A createConicGradient instance

In this example, we'll define two unlike conic gradients. A conic slope differs from a radial gradient equally, instead of creating circles, information technology circles around a signal.

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  certificate.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  // Create gradients                  var                  conicGrad1                  =                  ctx.                  createConicGradient                  (                  two                  ,                  62                  ,                  75                  )                  ;                  conicGrad1.                  addColorStop                  (                  0                  ,                  '#A7D30C'                  )                  ;                  conicGrad1.                  addColorStop                  (                  1                  ,                  '#fff'                  )                  ;                  var                  conicGrad2                  =                  ctx.                  createConicGradient                  (                  0                  ,                  187                  ,                  75                  )                  ;                  // we multiple our values by Math.PI/180 to catechumen degrees to radians                  conicGrad2.                  addColorStop                  (                  0                  ,                  'blackness'                  )                  ;                  conicGrad2.                  addColorStop                  (                  0.25                  ,                  'black'                  )                  ;                  conicGrad2.                  addColorStop                  (                  0.25                  ,                  'white'                  )                  ;                  conicGrad2.                  addColorStop                  (                  0.five                  ,                  'white'                  )                  ;                  conicGrad2.                  addColorStop                  (                  0.5                  ,                  'blackness'                  )                  ;                  conicGrad2.                  addColorStop                  (                  0.75                  ,                  'black'                  )                  ;                  conicGrad2.                  addColorStop                  (                  0.75                  ,                  'white'                  )                  ;                  conicGrad2.                  addColorStop                  (                  i                  ,                  'white'                  )                  ;                  // draw shapes                  ctx.fillStyle                  =                  conicGrad1;                  ctx.                  fillRect                  (                  12                  ,                  25                  ,                  100                  ,                  100                  )                  ;                  ctx.fillStyle                  =                  conicGrad2;                  ctx.                  fillRect                  (                  137                  ,                  25                  ,                  100                  ,                  100                  )                  ;                  }                              

The first gradient is positioned in the centre of the first rectangle and moves a green colour stop at the starting time, to a white i at the stop. The bending starts at 2 radians, which is noticeable because of the beginning/stop line pointing due south eastward.

The 2d gradient is also positioned at the center of it's 2d rectangle. This one has multiple colour stops, alternating from black to white at each quarter of the rotation. This gives us the checkered upshot.

Patterns

In i of the examples on the previous page, we used a series of loops to create a pattern of images. There is, nonetheless, a much simpler method: the createPattern() method.

createPattern(epitome, type)

Creates and returns a new canvas pattern object. image is a CanvasImageSource (that is, an HTMLImageElement, another canvas, a <video> element, or the like. type is a string indicating how to apply the epitome.

The blazon specifies how to apply the image in club to create the pattern, and must exist one of the following string values:

repeat

Tiles the image in both vertical and horizontal directions.

repeat-x

Tiles the image horizontally but not vertically.

repeat-y

Tiles the image vertically just not horizontally.

no-echo

Doesn't tile the epitome. Information technology's used only once.

We apply this method to create a CanvasPattern object which is very similar to the gradient methods we've seen above. In one case we've created a pattern, we tin assign it to the fillStyle or strokeStyle properties. For case:

                                  var                  img                  =                  new                  Epitome                  (                  )                  ;                  img.src                  =                  'someimage.png'                  ;                  var                  ptrn                  =                  ctx.                  createPattern                  (img,                  'repeat'                  )                  ;                              

Note: Similar with the drawImage() method, you must make sure the image you use is loaded earlier calling this method or the pattern may be fatigued incorrectly.

A createPattern instance

In this last instance, nosotros'll create a pattern to assign to the fillStyle belongings. The simply thing worth noting is the apply of the image'due south onload handler. This is to brand sure the paradigm is loaded before it is assigned to the pattern.

                                  part                  describe                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  // create new prototype object to use every bit pattern                  var                  img                  =                  new                  Image                  (                  )                  ;                  img.src                  =                  'canvas_createpattern.png'                  ;                  img.                  onload                  =                  function                  (                  )                  {                  // create design                  var                  ptrn                  =                  ctx.                  createPattern                  (img,                  'repeat'                  )                  ;                  ctx.fillStyle                  =                  ptrn;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  }                  }                              

Shadows

Using shadows involves just four properties:

shadowOffsetX = float

Indicates the horizontal altitude the shadow should extend from the object. This value isn't afflicted by the transformation matrix. The default is 0.

shadowOffsetY = bladder

Indicates the vertical distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.

shadowBlur = float

Indicates the size of the blurring consequence; this value doesn't correspond to a number of pixels and is non afflicted by the current transformation matrix. The default value is 0.

shadowColor = colour

A standard CSS color value indicating the color of the shadow result; by default, it is fully-transparent blackness.

The properties shadowOffsetX and shadowOffsetY signal how far the shadow should extend from the object in the X and Y directions; these values aren't afflicted past the electric current transformation matrix. Use negative values to crusade the shadow to extend up or to the left, and positive values to crusade the shadow to extend down or to the right. These are both 0 by default.

The shadowBlur property indicates the size of the blurring upshot; this value doesn't correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.

The shadowColor property is a standard CSS color value indicating the color of the shadow outcome; by default, it is fully-transparent black.

A adumbral text example

This example draws a text cord with a shadowing effect.

                                  office                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  ctx.shadowOffsetX                  =                  2                  ;                  ctx.shadowOffsetY                  =                  ii                  ;                  ctx.shadowBlur                  =                  2                  ;                  ctx.shadowColor                  =                  'rgba(0, 0, 0, 0.five)'                  ;                  ctx.font                  =                  '20px Times New Roman'                  ;                  ctx.fillStyle                  =                  'Blackness'                  ;                  ctx.                  fillText                  (                  'Sample String'                  ,                  v                  ,                  30                  )                  ;                  }                              

We will look at the font property and fillText method in the next chapter nearly cartoon text.

Canvas make full rules

When using fill (or clip and isPointInPath) you can optionally provide a fill rule algorithm by which to determine if a betoken is inside or exterior a path and thus if information technology gets filled or non. This is useful when a path intersects itself or is nested.

Two values are possible:

  • "nonzero" : The non-goose egg winding rule, which is the default rule.
  • "evenodd" : The even-odd winding rule.

In this example we are using the evenodd rule.

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'sail'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  ctx.                  beginPath                  (                  )                  ;                  ctx.                  arc                  (                  l                  ,                  50                  ,                  xxx                  ,                  0                  ,                  Math.                  PI                  *                  two                  ,                  true                  )                  ;                  ctx.                  arc                  (                  l                  ,                  50                  ,                  xv                  ,                  0                  ,                  Math.                  PI                  *                  2                  ,                  true                  )                  ;                  ctx.                  fill up                  (                  'evenodd'                  )                  ;                  }                              
  • « Previous
  • Side by side »

cheeketreas1959.blogspot.com

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