banner



How To Rotate A Drawing On Canvas Javascript

Transformations

  • « Previous
  • Side by side »

Earlier in this tutorial we've learned well-nigh the canvas grid and the coordinate space. Until at present, we simply used the default grid and inverse the size of the overall sail for our needs. With transformations there are more powerful means to translate the origin to a different position, rotate the filigree and even calibration it.

Saving and restoring country

Earlier we look at the transformation methods, let's look at two other methods which are indispensable once y'all start generating ever more circuitous drawings.

salvage()

Saves the entire state of the canvass.

restore()

Restores the near recently saved canvas country.

Sail states are stored on a stack. Every time the salvage() method is chosen, the current drawing state is pushed onto the stack. A drawing state consists of

  • The transformations that have been practical (i.due east. translate, rotate and scale – meet below).
  • The current values of the post-obit attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled.
  • The current clipping path, which we'll see in the side by side section.

You tin can telephone call the relieve() method as many times as you like. Each fourth dimension the restore() method is called, the last saved land is popped off the stack and all saved settings are restored.

A save and restore sail state example

This example tries to illustrate how the stack of drawing states functions past drawing a set up of consecutive rectangles.

                                  function                  describe                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'sheet'                  )                  .                  getContext                  (                  '2nd'                  )                  ;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  150                  ,                  150                  )                  ;                  // Draw a rectangle with default settings                  ctx.                  salvage                  (                  )                  ;                  // Save the default land                  ctx.fillStyle                  =                  '#09F'                  ;                  // Make changes to the settings                  ctx.                  fillRect                  (                  15                  ,                  15                  ,                  120                  ,                  120                  )                  ;                  // Depict a rectangle with new settings                  ctx.                  relieve                  (                  )                  ;                  // Save the current state                  ctx.fillStyle                  =                  '#FFF'                  ;                  // Brand changes to the settings                  ctx.globalAlpha                  =                  0.5                  ;                  ctx.                  fillRect                  (                  thirty                  ,                  thirty                  ,                  ninety                  ,                  90                  )                  ;                  // Draw a rectangle with new settings                  ctx.                  restore                  (                  )                  ;                  // Restore previous state                  ctx.                  fillRect                  (                  45                  ,                  45                  ,                  sixty                  ,                  60                  )                  ;                  // Draw a rectangle with restored settings                  ctx.                  restore                  (                  )                  ;                  // Restore original state                  ctx.                  fillRect                  (                  sixty                  ,                  60                  ,                  30                  ,                  30                  )                  ;                  // Draw a rectangle with restored settings                  }                              

The first pace is to depict a large rectangle with the default settings. Next nosotros save this country and make changes to the fill colour. Nosotros then draw the 2nd and smaller blue rectangle and save the state. Over again we alter some drawing settings and depict the third semi-transparent white rectangle.

So far this is pretty similar to what nosotros've done in previous sections. However once we call the showtime restore() statement, the tiptop cartoon state is removed from the stack, and settings are restored. If we hadn't saved the state using salvage(), we would need to change the fill color and transparency manually in lodge to return to the previous state. This would be easy for two properties, but if we have more than that, our code would become very long, very fast.

When the second restore() argument is called, the original state (the one we set up before the offset call to save) is restored and the last rectangle is in one case again drawn in black.

Translating

The first of the transformation methods we'll wait at is translate(). This method is used to move the canvas and its origin to a different point in the grid.

translate(x, y)

Moves the canvas and its origin on the grid. x indicates the horizontal distance to motion, and y indicates how far to move the grid vertically.

It's a good idea to relieve the canvas state earlier doing any transformations. In most cases, information technology is merely easier to telephone call the restore method than having to practice a reverse translation to return to the original land. Also if y'all're translating inside a loop and don't salve and restore the sheet country, y'all might end up missing office of your drawing, considering it was drawn outside the canvas edge.

A interpret case

This example demonstrates some of the benefits of translating the canvass origin. Without the translate() method, all of the rectangles would exist drawn at the same position (0,0). The translate() method also gives us the freedom to identify the rectangle anywhere on the canvass without having to manually conform coordinates in the fillRect() office. This makes it a little easier to empathize and use.

In the draw() role, we telephone call the fillRect() part nine times using two for loops. In each loop, the sheet is translated, the rectangle is drawn, and the canvass is returned back to its original country. Note how the phone call to fillRect() uses the aforementioned coordinates each time, relying on interpret() to adjust the cartoon position.

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <                  three                  ;                  i++                  )                  {                  for                  (                  var                  j                  =                  0                  ;                  j                  <                  3                  ;                  j++                  )                  {                  ctx.                  save                  (                  )                  ;                  ctx.fillStyle                  =                  'rgb('                  +                  (                  51                  *                  i)                  +                  ', '                  +                  (                  255                  -                  51                  *                  i)                  +                  ', 255)'                  ;                  ctx.                  interpret                  (                  10                  +                  j                  *                  fifty                  ,                  x                  +                  i                  *                  50                  )                  ;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  25                  ,                  25                  )                  ;                  ctx.                  restore                  (                  )                  ;                  }                  }                  }                              

Rotating

The second transformation method is rotate(). Nosotros utilise information technology to rotate the sail around the current origin.

rotate(angle)

Rotates the canvass clockwise around the current origin past the angle number of radians.

The rotation center indicate is always the sail origin. To change the center betoken, we will need to move the canvas by using the translate() method.

A rotate example

In this example, we'll use the rotate() method to first rotate a rectangle from the canvas origin and then from the center of the rectangle itself with the help of interpret().

Annotation: Angles are in radians, non degrees. To convert, nosotros are using: radians = (Math.PI/180)*degrees.

                                  function                  draw                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  // left rectangles, rotate from canvas origin                  ctx.                  save                  (                  )                  ;                  // bluish rect                  ctx.fillStyle                  =                  '#0095DD'                  ;                  ctx.                  fillRect                  (                  thirty                  ,                  30                  ,                  100                  ,                  100                  )                  ;                  ctx.                  rotate                  (                  (Math.                  PI                  /                  180                  )                  *                  25                  )                  ;                  // grey rect                  ctx.fillStyle                  =                  '#4D4E53'                  ;                  ctx.                  fillRect                  (                  30                  ,                  30                  ,                  100                  ,                  100                  )                  ;                  ctx.                  restore                  (                  )                  ;                  // right rectangles, rotate from rectangle middle                  // draw blueish rect                  ctx.fillStyle                  =                  '#0095DD'                  ;                  ctx.                  fillRect                  (                  150                  ,                  30                  ,                  100                  ,                  100                  )                  ;                  ctx.                  translate                  (                  200                  ,                  80                  )                  ;                  // translate to rectangle center                  // x = x + 0.5 * width                  // y = y + 0.5 * height                  ctx.                  rotate                  (                  (Math.                  PI                  /                  180                  )                  *                  25                  )                  ;                  // rotate                  ctx.                  translate                  (                  -                  200                  ,                  -                  lxxx                  )                  ;                  // interpret back                  // draw grey rect                  ctx.fillStyle                  =                  '#4D4E53'                  ;                  ctx.                  fillRect                  (                  150                  ,                  30                  ,                  100                  ,                  100                  )                  ;                  }                              

To rotate the rectangle around its own center, we interpret the canvas to the center of the rectangle, and then rotate the canvas, and so interpret the canvass back to 0,0, and and then depict the rectangle.

Scaling

The adjacent transformation method is scaling. We utilize it to increase or decrease the units in our sheet filigree. This can be used to describe scaled down or enlarged shapes and bitmaps.

scale(x, y)

Scales the canvas units by x horizontally and by y vertically. Both parameters are real numbers. Values that are smaller than 1.0 reduce the unit size and values above i.0 increase the unit size. Values of 1.0 leave the units the aforementioned size.

Using negative numbers you lot can practise axis mirroring (for instance using interpret(0,sail.height); scale(i,-one); you lot will have the well-known Cartesian coordinate organization, with the origin in the bottom left corner).

By default, ane unit on the canvas is exactly one pixel. If nosotros utilise, for instance, a scaling cistron of 0.v, the resulting unit would become 0.five pixels and then shapes would be drawn at half size. In a like fashion setting the scaling factor to 2.0 would increase the unit of measurement size and one unit now becomes 2 pixels. This results in shapes being drawn twice as large.

A scale example

In this concluding case, we'll draw shapes with unlike scaling factors.

                                  function                  depict                  (                  )                  {                  var                  ctx                  =                  document.                  getElementById                  (                  'canvas'                  )                  .                  getContext                  (                  'second'                  )                  ;                  // depict a simple rectangle, but scale it.                  ctx.                  save                  (                  )                  ;                  ctx.                  scale                  (                  10                  ,                  3                  )                  ;                  ctx.                  fillRect                  (                  1                  ,                  10                  ,                  10                  ,                  10                  )                  ;                  ctx.                  restore                  (                  )                  ;                  // mirror horizontally                  ctx.                  calibration                  (                  -                  1                  ,                  ane                  )                  ;                  ctx.font                  =                  '48px serif'                  ;                  ctx.                  fillText                  (                  'MDN'                  ,                  -                  135                  ,                  120                  )                  ;                  }                              

Transforms

Finally, the post-obit transformation methods permit modifications directly to the transformation matrix.

transform(a, b, c, d, due east, f)

Multiplies the electric current transformation matrix with the matrix described by its arguments. The transformation matrix is described past:

[ a c due east b d f 0 0 one ] \left[ \begin{array}{ccc} a & c & e \ b & d & f \ 0 & 0 & i \end{array} \correct]

If whatsoever of the arguments are Infinity the transformation matrix must be marked as space instead of the method throwing an exception.

The parameters of this function are:

a (m11)

Horizontal scaling.

b (m12)

Horizontal skewing.

c (m21)

Vertical skewing.

d (m22)

Vertical scaling.

eastward (dx)

Horizontal moving.

f (dy)

Vertical moving.

setTransform(a, b, c, d, e, f)

Resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments. This basically undoes the current transformation, and then sets the specified transform, all in 1 footstep.

resetTransform()

Resets the current transform to the identity matrix. This is the aforementioned equally calling: ctx.setTransform(ane, 0, 0, 1, 0, 0);

Example for transform and setTransform

                                  part                  draw                  (                  )                  {                  var                  ctx                  =                  certificate.                  getElementById                  (                  'sail'                  )                  .                  getContext                  (                  '2d'                  )                  ;                  var                  sin                  =                  Math.                  sin                  (Math.                  PI                  /                  half dozen                  )                  ;                  var                  cos                  =                  Math.                  cos                  (Math.                  PI                  /                  6                  )                  ;                  ctx.                  translate                  (                  100                  ,                  100                  )                  ;                  var                  c                  =                  0                  ;                  for                  (                  var                  i                  =                  0                  ;                  i                  <=                  12                  ;                  i++                  )                  {                  c                  =                  Math.                  floor                  (                  255                  /                  12                  *                  i)                  ;                  ctx.fillStyle                  =                  'rgb('                  +                  c                  +                  ', '                  +                  c                  +                  ', '                  +                  c                  +                  ')'                  ;                  ctx.                  fillRect                  (                  0                  ,                  0                  ,                  100                  ,                  10                  )                  ;                  ctx.                  transform                  (cos,                  sin,                  -sin,                  cos,                  0                  ,                  0                  )                  ;                  }                  ctx.                  setTransform                  (                  -                  i                  ,                  0                  ,                  0                  ,                  1                  ,                  100                  ,                  100                  )                  ;                  ctx.fillStyle                  =                  'rgba(255, 128, 255, 0.5)'                  ;                  ctx.                  fillRect                  (                  0                  ,                  50                  ,                  100                  ,                  100                  )                  ;                  }                              
  • « Previous
  • Next »

How To Rotate A Drawing On Canvas Javascript,

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

Posted by: rountreeandestalmoss.blogspot.com

0 Response to "How To Rotate A Drawing On Canvas Javascript"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel