EN
JavaScript - scale drawing on canvas
0 points
In this article, we would like to show you how to
Quick solution:
xxxxxxxxxx
1
var canvas = document.querySelector('#canvas');
2
var context = canvas.getContext('2d');
3
context.scale(0.5, 1.5); // scale(x, y)
In this example, we use scale()
method to add a scaling transformation to the canvas2
units horizontally and vertically.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<div>Original:</div>
12
<canvas id="canvas1" width="200" height="200"></canvas>
13
<br>
14
<div>Scaled:</div>
15
<canvas id="canvas2" width="200" height="200"></canvas>
16
<script>
17
18
var canvas1 = document.querySelector('#canvas1');
19
var canvas2 = document.querySelector('#canvas2');
20
21
var context1 = canvas1.getContext('2d');
22
var context2 = canvas2.getContext('2d');
23
24
// -------------------------------------------------------------
25
// drawSquare source: https://dirask.com/posts/DKL5gp
26
27
function drawSquare(context, x, y, side) {
28
context.strokeStyle = 'red';
29
context.beginPath();
30
context.rect(x, y, side, side); // rect(x, y, width, height)
31
context.stroke();
32
}
33
34
// -------------------------------------------------------------
35
36
drawSquare(context1, 30, 30, 100);
37
38
// scale canvas x-axis * 0.5 and y-axis * 1.2
39
context2.scale(0.5, 1.2);
40
41
drawSquare(context2, 30, 30, 100);
42
43
</script>
44
</body>
45
</html>