HTML canvas translate() Method

Introduction

Draw a rectangle in position (10,10), set new (0,0) position to (70,70).

View in separate window

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="180" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillRect(10, 10, 100, 50);/*  w  w w  .j a  va2 s.com*/
ctx.translate(70, 70);
ctx.fillRect(10, 10, 100, 50);
</script>

</body>
</html>

The translate() method remaps the (0,0) position on the canvas.

When you call a method such as fillRect() after translate(), the value is added to the x- and y-coordinate values.

context.translate(x, y);

Parameter Values

You can specify one or both parameters.

Parameter Description
x The value to add to horizontal (x) coordinates
y The value to add to vertical (y) coordinates



PreviousNext

Related