【实战】手把手教你使用canvas 绘制足球 —— 第一步 画个球体


一、球体分析

先上两张图
在这里插入图片描述

在这里插入图片描述

x = ρ × s i n ( φ ) × c o s ( θ ) x = \rho \times sin(\varphi) \times cos(\theta) x=ρ×sin(φ)×cos(θ)
y = ρ × s i n ( φ ) × s i n ( θ ) y = \rho \times sin(\varphi) \times sin(\theta) y=ρ×sin(φ)×sin(θ)
z = ρ × c o s ( φ ) z = \rho \times cos(\varphi) z=ρ×cos(φ)

φ = a c o s ( k ) \varphi = acos(k) φ=acos(k)
θ = φ × n × π \theta = \varphi \times \sqrt{n \times \pi} θ=φ×n×π

二、足球结构分析

传统足球是以皮革或其它合适的材料制成,即20块正六边形(白)和12块正五边形(黑)一共32块皮组成,也就是5:3的比例.,顶点数为60,棱数为90

三、canvas常用API

  • save:将当前状态放入栈中,保存 canvas 全部状态;
  • beginPath:清空子路径列表开始一个新路径;
  • arc:圆弧路径的圆心在 (x, y) 位置,半径为 r,根据指定的方向从 startAngle 开始绘制,到 endAngle 结束。
  • fillStyle:填充样式
  • fill:根据当前的填充样式,填充当前或已存在的路径
  • restore:将 canvas 恢复到最近的保存状态

四、画个球体

1.初始化

  • 来个官网示例:
<!DOCTYPE html>
<html>
<body>
  <canvas id='cas' width="1000" height="500"></canvas>
</body>
<script>
  let canvas = document.getElementById("cas"),
  let ctx = canvas.getContext("2d")
      
  ctx.fillStyle = "rgb(200,0,0)";
  ctx.fillRect (10, 10, 55, 50);

  ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
  ctx.fillRect (30, 30, 55, 50);
</script>
</html>

在这里插入图片描述

没有设置宽度和高度的时候,canvas 会初始化宽度为 300 像素和高度为 150 像素(用 width 和 height 属性为<canvas>明确规定宽高,而不是使用 CSS,否则可能会扭曲变形)

2.代码

 body{
    
    
   background-color: black;
 }
let canvas = document.getElementById("cas"),
      ctx = canvas.getContext("2d")
      // 球心位置
      vpx = window.innerWidth / 2,
      vpy = window.innerHeight / 2,
      // 球体半径
      Radius = 150,
      points = [],
      angleX = Math.PI / 100,
      angleY = Math.PI / 100;

  let Animation = function() {
    
    
    points = [];
    // 点的数量
    let num = 500;
    for (let i = 0; i <= num; i++) {
    
    
      let k = -1 + 0.004*i;
      let a = Math.acos(k);
      var b = a * Math.sqrt(num * Math.PI);
      var x = Radius * Math.sin(a) * Math.cos(b);
      var y = Radius * Math.sin(a) * Math.sin(b);
      var z = Radius * Math.cos(a);
      var b = new point(x, y, z, 1.5);
      points.push(b);
      b.paint();
    }
  }

// 单个点的构造方法(包含三个坐标值,半径,直径)
  var point = function(x, y, z, r) {
    
    
    this.x = x;
    this.y = y;
    this.z = z;
    this.r = r;
    this.width = 2 * r;
  }

// point在原型链上增加paint方法
  point.prototype = {
    
    
    paint: function() {
    
    
      var fl = 450
      // 保存当前状态
      ctx.save();
      // 开始新路径的绘制
      ctx.beginPath();
      // 缩放值(1.5 ~ 0.5)
      var scale = fl / (fl - this.z);
      // 透明度值(1 ~ 0)
      var alpha = (this.z + Radius) / (2 * Radius);
      // 单个点绘制(半径根据焦距比例进行缩放)
      ctx.arc(vpx + this.x, vpy + this.y, this.r * scale, 0, 2 * Math.PI, true);
      // 单个点的透明度进行参数配置,越远越浅
      ctx.fillStyle = "rgba(255,255,255," + (alpha + 0.5) + ")"
      // 根据填充样式填充路径
      ctx.fill();
      // ctx.restore();
    }
  }

  Animation()

在这里插入图片描述

五、加上足球的皮肤

未完待续。。。


猜你喜欢

转载自blog.csdn.net/qq_32682301/article/details/128254573