欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

canvas绘制钟表

程序员文章站 2022-05-28 10:06:42
...

要绘制路径,首先必须调用 beginPath() 方法,表示要开始绘制新路径。

<html>
  <body>
    <canvas id="drawing" width="500" height="500">Is drawing of something</canvas>

    <script>
      var drawing = document.getElementById('drawing');
      // 确认浏览器支持canvas元素
      if (drawing.getContext) {
        var context = drawing.getContext('2d');
        // 开始路径
        context.beginPath();
        // 绘制外圆
        context.arc(250, 100, 99, 0, 2*Math.PI, false);
        // 绘制内圆
        context.moveTo(344, 100);
        context.arc(250, 100, 94, 0, 2*Math.PI, false);
        // 绘制数字
        context.font = "bold 14px Arial";
        context.textAlign = "center";
        context.textBaseline = "middle";
        context.fillText("12", 250, 20);
        context.fillText("9", 170, 100);
        // 旋转
        // context.rotate(1);
        // 绘制分针
        context.moveTo(250, 100);
        context.lineTo(250, 30);
        // 绘制时针
        context.moveTo(250, 100);
        context.lineTo(190, 100);
        // 描边路径
        context.stroke();
        
        if (context.isPointInPath(250, 6)) {
          console.log("point (250, 6) is in the path");
        } else {
          console.log("point (250, 6) isn't in the path");
        }

        var imgURL = drawing.toDataURL("image/png");
        var image = document.createElement("img");
        image.src = imgURl;
        document.body.appendChild(image);

      }
      
    </script>
  </body>
</html>

效果图:
canvas绘制钟表