首先介绍下这个函数
context.arcTo(x1, y1, x2, y2, r);
其中x1为弧的起点x坐标;
其中y1为弧的起点y坐标;
其中x2为弧的终点x坐标;
其中y2为弧的终点y坐标;
其中r为弧的半径。
程序运行截图如下:
源码如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
-
- <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
- 当前浏览器不支持canvas
- </canvas>
-
- <script>
-
- window.onload = function(){
-
- let canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 800;
- let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
-
- context.beginPath();
- context.moveTo(150, 150);
- context.arcTo(650, 150, 650, 650, 300);
- context.lineWidth = 6;
- context.strokeStyle = "red";
- context.stroke();
-
-
- //baseline
- context.beginPath();
- context.moveTo(150, 150);
- context.lineTo(650, 150);
- context.lineTo(650, 650);
-
- context.lineWidth = 2;
- context.strokeStyle = "gray";
- context.stroke();
- }
-
-
- </script>
-
- </body>
- </html>
下面是绘制给弯月
程序运行截图如下:
源码如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
-
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
-
- <canvas id="canvas" style="border: 1px solid #aaa; display: block; margin: 50px auto;">
- 当前浏览器不支持canvas
- </canvas>
-
- <script>
-
- window.onload = function(){
-
- let canvas = document.getElementById("canvas");
- canvas.width = 800;
- canvas.height = 800;
- let context = canvas.getContext("https://cdn.jxasp.com:9143/image/2d");
-
-
- context.arc(400, 400, 300, 0.5 * Math.PI, 1.5 * Math.PI, true);
- context.moveTo(400, 100);
- context.arcTo(1200, 400, 400, 700, (400 - 100) * dis(400, 100, 1200, 400) / (1200 - 400));
- context.stroke();
- }
-
- function dis(x1, y1, x2, y2){
-
- return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
- }
-
-
- </script>
-
- </body>
- </html>
-
- </body>
- </html>
这里月亮最左边的那条边是圆弧,正园,不是椭圆,所以一开始使用arc去画给半圆,然后再使用arcTo去画弧。
这里来说下arcTo中半径是怎么算的
也就是(400 - 100) * dis(400, 100, 1200, 400) / (1200 - 400)
这里aco的tan为AH/HC也为R/AC
也就是R = (AH * AC) / HC
这个AH为400 - 100
AC为AH平方+HC的平方 开根号,也就是dis中的计算
HC为1200 - 400