![](https://img.haomeiwen.com/i7455247/7126e2331462f22d.png)
三角函数在canvas绘制图形很有用。比如,如何画一个等边三角形呢?
![](https://img.haomeiwen.com/i7455247/bcc9b23775c420ce.png)
利用三角函数,我们可以轻松搞定。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<canvas id="canvas" width="300" height="200" style="border:1px dashed gray;">
</canvas>
</body>
</html>
<script>
window.onload = function () {
var cnv = document.getElementById("canvas");
var cxt = cnv.getContext("2d");
drawTriangle(cxt,50);
}
function drawTriangle(cxt, radius) {
cxt.beginPath();
cxt.lineTo(Math.cos(0) * radius, Math.sin(0) * radius);
cxt.lineTo(Math.cos(2 * Math.PI / 3) * radius, Math.sin(2 * Math.PI / 3) * radius);
cxt.lineTo(Math.cos(4 * Math.PI / 3) * radius, Math.sin(4 * Math.PI / 3) * radius);
cxt.closePath();
cxt.fill();
}
</script>
ACB三个点对应的,分别是0,2π/3和4π/3。
![](https://img.haomeiwen.com/i7455247/1970bad76c6288aa.png)
其实画出来的就是对应坐标中的这个三角形:
![](https://img.haomeiwen.com/i7455247/4104484a0771ee13.png)
因为负坐标轴的那部分无法展示,我们可以通过平移坐标展示出来。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<canvas id="canvas" width="300" height="200" style="border:1px dashed gray;">
</canvas>
</body>
</html>
<script>
window.onload = function () {
var cnv = document.getElementById("canvas");
var cxt = cnv.getContext("2d");
drawTriangle2(cxt,50,100);
}
function drawTriangle2(cxt, radius,offset) {
cxt.beginPath();
cxt.lineTo(Math.cos(0) * radius + offset, Math.sin(0) * radius + offset);
cxt.lineTo(Math.cos(2 * Math.PI / 3) * radius + offset, Math.sin(2 * Math.PI / 3) * radius + offset);
cxt.lineTo(Math.cos(4 * Math.PI / 3) * radius + offset, Math.sin(4 * Math.PI / 3) * radius + offset);
cxt.closePath();
cxt.fill();
}
</script>
x轴和y轴都平移了100px,就可以得到一个完整的等边三角形了。
![](https://img.haomeiwen.com/i7455247/395e5d647cc82f40.png)
网友评论