根据输入的角度动态变化
html代码
<div>
<input id="input" type="text" placeholder="输入任意角度" />
<button>确定</button>
</div>
<canvas id="css"></canvas>
1. 画直角坐标系
window.onload = (event) => {
// console.log(event);
main();
};
let ccs;
let ccsContext;
function main() {
ccs = document.querySelector("#css");
// 设置画布的宽高
ccs.width = 200;
ccs.height = 200;
ccsContext = ccs.getContext("2d");
ccsContext.translate(ccs.width / 2, ccs.height / 2); // 使画布的起点向左移动 ccs.width / 2 像素,向下移动 ccs.height / 2 像素,使其起点位于画布中心
// 画直线
drawLine(ccsContext, 0, 0, ccs.width / 2, 0); // x轴正半轴
drawLine(ccsContext, 0, 0, -ccs.width / 2, 0); // x轴负半轴
drawLine(ccsContext, 0, 0, 0, ccs.height / 2); // y轴正半轴
drawLine(ccsContext, 0, 0, 0, -ccs.height / 2); // y轴负半轴
fillTriangle(
ccsContext,
ccs.width / 2 - 10,
5,
ccs.width / 2,
0,
ccs.width / 2 - 10,
-5
); // x轴箭头
fillTriangle(
ccsContext,
5,
ccs.height / 2 - 10,
0,
ccs.height / 2,
-5,
ccs.height / 2 - 10
); // y轴箭头
}
画直线和画小三角方法
function drawLine(canvasContext, x0, y0, x1, y1, color) {
canvasContext.beginPath();
canvasContext.moveTo(x0, -y0);
canvasContext.lineTo(x1, -y1); // 画笔的终点,第一个参数表示向左移动 xx 像素,,第二个参数表示向下移动 yy 像素
canvasContext.strokeStyle = color; // 该样式需写在.stroke前面
canvasContext.stroke();
}
function fillTriangle(canvasContext, x0, y0, x1, y1, x2, y2, color) {
canvasContext.beginPath();
canvasContext.moveTo(x0, -y0);
canvasContext.lineTo(x1, -y1);
canvasContext.lineTo(x2, -y2);
canvasContext.closePath();
canvasContext.fillStyle = color;
canvasContext.fill();
}
2. 画角度
function drawAngle(angle = 30, r = 30) {
// 画角度线
drawLine(
ccsContext,
0,
0,
(ccs.height / 2) * Math.sin(getHud(angle)),
(ccs.width / 2) * Math.cos(getHud(angle)),
"red"
);
let l = Math.sqrt(25 + (ccs.height / 2 - 10) * (ccs.height / 2 - 10));
let pAngle = 3;
fillTriangle(
ccsContext,
l * Math.sin(getHud(angle - pAngle)),
l * Math.cos(getHud(angle - pAngle)),
l * Math.sin(getHud(angle + pAngle)),
l * Math.cos(getHud(angle + pAngle)),
(ccs.height / 2) * Math.sin(getHud(angle)),
(ccs.width / 2) * Math.cos(getHud(angle)),
"red"
); // 角度线箭头
// 画弧度
ccsContext.beginPath();
ccsContext.arc(
0,
0,
20,
hypotenuse(ccs.width / 2, 90 - angle),
1.5 * Math.PI,
true
);
//画文字
ccsContext.font = "10px Arial";
//计算文字位置
radians = angle * (Math.PI / 180); //角度转弧度
ccsContext.fillText(
angle + "°",
r * Math.sin(radians / 2) - 5,
-(r * Math.cos(radians / 2) - 5)
);
ccsContext.stroke();
}
//换算小弧度的大小
function hypotenuse(r, angle) {
return (2 - angle / 180) * Math.PI;
}
//换算角度对应的弧度
function getHud(angle) {
return (angle / 180) * Math.PI;
}
document.querySelector("button").onclick = doit; //点击事件
function doit() {
ccsContext.clearRect(0, 0, ccs.width, ccs.height); //清除整个画布
main(); // 重新绘制直角坐标系
let value = document.getElementById("input").value * 1;
drawAngle(value); // 画角度
}