ZBLOG

js 使用canvas绘制方位图并标注刻度,刻度显示朝外,正上方角度为0°,正右边角度为90°,依次顺时针

以下是使用 JavaScript 和 Canvas 绘制方位图并标注刻度的示例代码:

<!DOCTYPE html>
<html>
  <head>
    <title>方位图</title>
    <style>
      canvas {
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <canvas id="compass" width="400" height="400"></canvas>

    <script>
      // 获取 canvas 元素
      const canvas = document.getElementById("compass");
      const ctx = canvas.getContext("2d");

      // 设置画布属性
      const centerX = canvas.width / 2;
      const centerY = canvas.height / 2;
      const radius = Math.min(centerX, centerY) - 10;

      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制方位图外圆
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
      ctx.stroke();

      // 绘制刻度
      for (let i = 0; i <= 360; i += 15) {
        const angle = ((i - 90) * Math.PI) / 180; // 将角度转换为弧度,将起始位置调整为正上方

        const startX = centerX + (radius - 20) * Math.cos(angle);
        const startY = centerY + (radius - 20) * Math.sin(angle);

        const endX = centerX + radius * Math.cos(angle);
        const endY = centerY + radius * Math.sin(angle);

        ctx.beginPath();
        ctx.moveTo(startX, startY);
        ctx.lineTo(endX, endY);
        ctx.stroke();

        // 标注刻度值
        ctx.font = "12px Arial";
        ctx.fillStyle = "#000";
        const textX = centerX + (radius - 40) * Math.cos(angle);
        const textY = centerY + (radius - 40) * Math.sin(angle);
        ctx.fillText(i.toString(), textX, textY);
      }
    </script>
  </body>
</html>

此代码会绘制一个半径为 radius 的圆,以 (centerX, centerY) 为中心点。然后在圆上绘制刻度,并标注对应的角度值。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8414

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?