canvas 从入门到放弃

年末终于闲了下来,看最近小游戏挺火的的就从新学习了一下canvas。
目标:canvas 绘制一个心形
需要函数:

配置粒子属性

const settings = {
   particles: {
      size: 30 // 粒子大小px
   }
}

生成X,Y

let Point = (function () {
      function Point(x, y) {
        this.x = (typeof x !== 'undefined') ? x : 0;
        this.y = (typeof y !== 'undefined') ? y : 0;
      }
      Point.prototype.clone = function () {
        return new Point(this.x, this.y);
      };
      Point.prototype.length = function (length) {
        // 不传length length = 开方(x的平方 + y平方) 
        if (typeof length == 'undefined')
          return Math.sqrt(this.x * this.x + this.y * this.y);
        
        // 传length 求x,y
        this.normalize();
        this.x *= length;
        this.y *= length;
        return this;
      };
      Point.prototype.normalize = function () {
        // 已知length x,y为比例,求实际x,y
        var length = this.length();
        this.x /= length;
        this.y /= length;
        return this;
      };
      return Point;
    })();

function pointOnHeart(t) {
      // -PI <= t <= PI    心形完整度
     return new Point(
         160 * Math.pow(Math.sin(t), 3),
         130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25
    )
}

绘制

let canvas = document.querySelector('canvas')
let ctx = canvas.getContext('2d')
let image = (function () {
        
        canvas.width = settings.particles.size;
        canvas.height = settings.particles.size;
        // helper function to create the path
        function to(t) {
          var point = pointOnHeart(t);
          point.x = settings.particles.size / 2 + point.x * settings.particles.size / 350;
          point.y = settings.particles.size / 2 - point.y * settings.particles.size / 350;
          return point;
        }
        // create the path
        ctx.beginPath();
        var t = -Math.PI;
        var point = to(t);
        ctx.moveTo(point.x, point.y);
        while (t < Math.PI) {
          t += 0.01; // baby steps!
          point = to(t);
          ctx.lineTo(point.x, point.y);
        }
        ctx.closePath();
        // create the fill
        ctx.fillStyle = '#ea80b0';
        ctx.fill();
        // create the image
        var image = new Image();
        image.src = canvas.toDataURL();
        return image;
      })();

完整代码





  
  
  
  Document




  
  


image.png

进阶

让一个心简单的动起来





  
  
  
  Document




  
  



未命名.gif

很多动起来





  
  
  
  Document




  
  



image.png

你可能感兴趣的:(canvas 从入门到放弃)