Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第112题(2019-12-24):请使用canvas画一个五角星。 #114

Open
qappleh opened this issue Dec 24, 2019 · 1 comment
Open

第112题(2019-12-24):请使用canvas画一个五角星。 #114

qappleh opened this issue Dec 24, 2019 · 1 comment
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Dec 24, 2019

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Dec 26, 2019

canvas是HTML5中新增的标签,用于绘制图形,实际上,这个标签和其他的标签一样,其特殊之处在于该标签可以获取一个CanvasRenderingContext2D对象,我们可以通过JavaScript脚本来控制该对象进行绘图。

canvas绘制五角星,其大致思路就是:
里面的五个点和外面的五个点为同一圆心,以该点为圆心,利用数学几何知识可知每个点角度,利用Math.cos()和Math.sin()可算出每个店的坐标,最后用lineTo把每个点连起来即成为了一个五角星。
完整示例代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>canvas绘制五角星 </title>
  <script type="text/javascript" >
    window.onload = function () {
      var canvas = document.getElementById("canvas");
      if (canvas) {
        var context = canvas.getContext("2d");
        drawStar(context, 50, 100, 100);
      } else {
        document.writeln("浏览器不支持canvas组件");
      }
    }
    function drawStar(context, r, x, y) {
      context.lineWidth = 5;
      context.beginPath();
      var dit = Math.PI * 4 / 5;
      var sin = Math.sin(0) * r + y;
      var cos = Math.cos(0) * r + x;
      console.log(0+":"+0);
      context.moveTo(cos, sin);
      for (var i = 0; i < 5; i++) {
        var tempDit = dit * i;
        sin = Math.sin(tempDit) * r + y;
        cos = Math.cos(tempDit) * r + x;
        context.lineTo(cos, sin);
        console.log(sin+":"+sin+":"+tempDit);
      }
      context.closePath();
      context.strokeStyle = "red";
      context.fillStyle = "#ffc107";
      context.fill();
    }
  </script>
</head>
<body>
<canvas id="canvas" ></canvas>
</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant