qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!

Home Page:https://github.com/qappleh/Interview

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

qappleh opened this issue · comments

commented
commented

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>