translate() 是 Canvas 2D API 通過在網(wǎng)格中移動 canvas 和 canvas 原點(diǎn) x 水平方向、原點(diǎn) y 垂直方向,添加平移變換的方法。
在位置(10,10)繪制一個矩形,將新的(0,0)位置設(shè)置為(70,70)。再次繪制相同的矩形(注意,矩形現(xiàn)在從(80,80)位置開始:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML canvas translate()方法使用-菜鳥教程(cainiaoplus.com)</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的瀏覽器不支持 HTML5 canvas 標(biāo)簽。
</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(10,10,100,50);
ctx.translate(70,70);
ctx.fillRect(10,10,100,50);
</script>
</body>
</html>測試看看 ?/?IEFirefoxOperaChromeSafari
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 translate() 方法。
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
translate() 方法重新映射畫布上的(0,0)位置。
注意:當(dāng)您在 translate() 之后調(diào)用諸如 fillRect() 之類的方法時,值會添加到 x 和 y 坐標(biāo)值上。

| JavaScript 語法: | context.translate(x,y); |
|---|
注意: You can specify one or both parameters.
| 參數(shù) | 描述 |
|---|---|
| x | 添加到水平坐標(biāo)(x)上的值。 |
| y | 添加到垂直坐標(biāo)(y)上的值。 |