Canvas Coordinates

Canvas Coordinates (画布坐标)

HTML canvas is a powerful element in HTML5 that allows you to create and manipulate graphics on a web page using JavaScript. The canvas element provides a two-dimensional drawing surface, which can be thought of as a grid or coordinate system. the upper-left corner of which has the coordinates (0,0). The X-axis increases horizontally to the right, and the Y-axis increases vertically downward. Each point in the canvas is represented by a pair of coordinates (x, y) that define its position within the grid.

Drawing a Line

Drawing a Line (绘制线条)

The methods below are used to draw a straight line on a canvas:

  • moveTo(x,y), which specifies the starting point of the line (- moveTo (x, y) ,指定线的起点)

  • lineTo(x,y), which specifies the ending point of the line (- lineTo (x, y) ,指定线的终点)

Use one of the “ink” methods to draw a line, for example, the stroke(). (使用其中一种“墨迹”方法绘制线条,例如笔划()。)

Example of the HTML <canvas> element to draw a line:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
 </head>
 <body>
   <canvas width="300" height="150" style="border:1px solid #cccccc;" id="canvasExample">
     Your browser does not support the HTML5 canvas tag.
(您的浏览器不支持HTML5标签。)
   </canvas>
   <script>
     var c = document.getElementById("canvasExample");

     var ctx = c.getContext("2d");

     ctx.moveTo(0, 0);

     ctx.lineTo(300, 150);

     ctx.strokeStyle = '#359900';
     ctx.stroke();

   </script>
 </body>
</html>

In the example above, we have defined the starting and ending points of the line, that we have used the stroke() method to draw it. (在上面的示例中,我们定义了直线的起点和终点,我们使用stroke ()方法来绘制它。)

Drawing a Circle

Drawing a Circle (绘制圆形)

The methods below are used to draw a circle on a canvas:

  • beginPath(), which begins a path (- beginPath () ,它开始一个路径)

  • arc(x,y,r,startangle,endangle), which creates an arc/curve. If you want to create a circle with arc(): set start angle to 0 and end angle to 2*Math.PI. The x and y specify the x- and y-coordinates of the circle’s center. The r parameter specifies the radius of the circle.

Example of the HTML <canvas> element to draw a circle:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
 </head>
 <body>
   <canvas id="exampleCanvas" width="250" height="200" style="border:1px solid #dddddd;">
     The canvas tag is not supported by your browser..
(您的浏览器不支持画布标签。)
   </canvas>
   <script>
     var canvas = document.getElementById("exampleCanvas");

     var ctx = canvas.getContext("2d");

     ctx.beginPath();

     ctx.arc(125, 95, 70, 0, 2 * Math.PI);

     ctx.strokeStyle = '#1c87c9';
     ctx.stroke();

   </script>
 </body>
</html>

In the example above, we have defined a circle with the arc() method and used the stroke() method to draw the circle. (在上面的示例中,我们使用arc ()方法定义了一个圆,并使用stroke ()方法绘制了圆。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部