Languages
[Edit]
EN

JavaScript - flip canvas both vertically and horizontally

0 points
Created by:
Zayaan-Rasmussen
543

In this article, we would like to show you how to flip canvas vertically and horizontally at once using JavaScript.

Quick solution:

var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');

context.scale (-1, -1); // <--- flip context

context.font = '55px Arial';
context.fillText('text', -100, -15);

Note:

The coordinates of all points inside the canvas are negative now.

 

Practical example

In this example, we use scale() method with negative coordinates to flip the text on canvas vertically and horizontally at once.  

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    #my-canvas { border: 1px solid gray; }

  </style>
</head>
<body>
  <canvas id="my-canvas" width="110" height="65"></canvas>
  <script>

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');

    context.scale (-1, -1); // <--- flip context

    context.font = '40pt Arial';
    context.fillText('text', -100, -15);

  </script>
</body>
</html>

See also

  1. JavaScript - draw text on canvas

References

  1. CanvasRenderingContext2D.scale() - Web APIs | MDN
  2. CanvasRenderingContext2D.fillText() - Web APIs | MDN

Alternative titles

  1. JavaScript- rotate canvas 180 degrees both x and y-axis
  2. JavaScript - get vertical and horizontal mirror image of canvas (x and y-axis reflection)
  3. JavaScript - flip canvas vertically and horizontally at once
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join