EN
JavaScript - translate drawing on canvas
0
points
In this article, we would like to show you how to translate drawing on canvas using JavaScript.
Quick solution:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.translate(50, -60);
// draw something
Practical example
In this example, we use translate()
method that moves the canvas and its origin x
and y
units by given value.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="300" height="200"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
function drawSquare(x, y, side, color) {
context.beginPath();
context.rect(x, y, side, side); // rect(x, y, width, height)
context.strokeStyle = color;
context.stroke();
}
drawSquare(50, 80, 100, 'green');
context.translate(50, -60);
drawSquare(50, 80, 100, 'red');
</script>
</body>
</html>
result: