EN
JavaScript - scale drawing on canvas
0
points
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>