我正在尝试使用canvas和javascript绘制一个垂直箭头。我可以画一个箭头向上,但发现很难将箭头放在底部。
我正在尝试的代码
<!DOCTYPE html>
<html>
<body>
<canvas id="c" width="500" height="500" style="border:1px solid grey"></canvas>
<script>
const ctx = document.getElementById("c").getContext("2d");
drawArrow(ctx, 300, 300, 300, 200);
function drawArrow(context, fromx, fromy, tox, toy) {
const headlen = 10; // length of head in pixels
const angle = Math.atan2(toy - fromy, tox - fromx);
context.beginPath();
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6));
context.moveTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6));
context.stroke();
}
</script>
</body>
</html>
我需要的是相同的箭头,它将放置在底部向下。
箭头生成在您找到的代码中已经是动态的。您所需要做的就是更改开始和结束位置的坐标。
改变
drawArrow(ctx, 300, 300, 300, 200);
至
drawArrow(ctx, 300, 200, 300, 300);
这是一个工作示例:
const ctx = document.getElementById("c").getContext("2d");
drawArrow(ctx, 300, 200, 300, 300);
function drawArrow(context, fromx, fromy, tox, toy) {
const headlen = 10; // length of head in pixels
const angle = Math.atan2(toy - fromy, tox - fromx);
context.beginPath();
context.moveTo(fromx, fromy);
context.lineTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6));
context.moveTo(tox, toy);
context.lineTo(tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6));
context.stroke();
}
<canvas id="c" width="500" height="500" style="border:1px solid grey"></canvas>