JavaScript - scale drawing on canvas

0 points
Created by:

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>
    canvas { border: 1px solid gray; }
  <canvas id="canvas1" width="200" height="200"></canvas>
  <canvas id="canvas2" width="200" height="200"></canvas>

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

    // -------------------------------------------------------------
    // drawSquare source:

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

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

    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);

See also

  1. JavaScript - draw square on canvas element


  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.

❤️💻 🙂