Languages
[Edit]
EN

JavaScript - scale drawing on canvas

0 points
Created by:
Vanessa-Drake
718

In this article, we would like to show you how to

Quick solution:

var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');
context.scale(0.5, 1.5); // scale(x, y)

 

Practical example

In this example, we use scale() method to add a scaling transformation to the canvas2 units horizontally and vertically.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    canvas { border: 1px solid gray; }
    
  </style>
</head>
<body>
  <div>Original:</div>
  <canvas id="canvas1" width="200" height="200"></canvas>
  <br>
  <div>Scaled:</div>
  <canvas id="canvas2" width="200" height="200"></canvas>
  <script>

    var canvas1 = document.querySelector('#canvas1');
    var canvas2 = document.querySelector('#canvas2');
    
    var context1 = canvas1.getContext('2d');
    var context2 = canvas2.getContext('2d');

    // -------------------------------------------------------------
    // drawSquare source: https://dirask.com/posts/DKL5gp

    function drawSquare(context, x, y, side) {
        context.strokeStyle = 'red';
        context.beginPath();
        context.rect(x, y, side, side); // rect(x, y, width, height)
        context.stroke();
    }

    // -------------------------------------------------------------

    drawSquare(context1, 30, 30, 100);
    
    // scale canvas x-axis * 0.5 and y-axis * 1.2
    context2.scale(0.5, 1.2);

    drawSquare(context2, 30, 30, 100);
    
  </script>
</body>
</html>

See also

  1. JavaScript - draw square on canvas element

References

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

Alternative titles

  1. JavaScript - transform HTML canvas using scale()
  2. JavaScript - scale drawing on HTML canvas
  3. JavaScript - scale HTML canvas context
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.

JavaScript - HTML5 canvas tutorial

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