English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
translate() 是 Canvas 2D API 通过在网格中移动 canvas 和 canvas 原点 x 水平方向、原点 y 垂直方向,添加平移变换的方法。
在位置(10,10)绘制一个矩形,将新的(0,0)位置设置为(70,70)。再次绘制相同的矩形(注意,矩形现在从(80,80)位置开始:
!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTML canvas translate()方法使用-基础教程(oldtoolbag.com)</title> </head> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3> 您的浏览器不支持 HTML5 canvas 标签。 </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>Test See ‹/›
IEFirefoxOperaChromeSafari
Internet Explorer 9and Firefox, Opera, Chrome, and Safari support translate(). Methods.
Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.
The translate() method remaps the (0,0) position on the canvas.
Note:When you call methods like fillRect() after translate(), the values are added to the x and y coordinate values.
JavaScript Syntax: | context.translate(x,y); |
---|
Note: You can specify one or both parameters.
Parameter | Description |
---|---|
x | Add the value to the horizontal coordinate (x). |
y | Add the value to the vertical coordinate (y). |