canvas 从入门到放弃

年末终于闲了下来,看最近小游戏挺火的的就从新学习了一下canvas。
目标:canvas 绘制一个心形
需要函数:
X=160 * Math.pow(Math.sin(t), 3),
Y= 130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25

配置粒子属性

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;
      })();

完整代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<style>
  * {
    margin: 0;
    padding: 0
  }
</style>

<body>
  <canvas></canvas>
  <script>
    const settings = {
      particles: {
        size: 30 // 粒子大小px
      }
    }
    let canvas = document.querySelector('canvas')
    let ctx = canvas.getContext('2d')

    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
        let 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 image = (function () {

      canvas.width = settings.particles.size;
      canvas.height = settings.particles.size;
      // 帮助创建路径函数
      function to(t) {
        let 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;
      }
      // 创建路径
      ctx.beginPath();
      let t = -Math.PI;
      let 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();
      // 添加填充
      ctx.fillStyle = '#ea80b0';
      ctx.fill();
      // 创建图像
      let image = new Image();
      image.src = canvas.toDataURL();
      return image;
    })();

  </script>
</body>
</html>
image.png

进阶

让一个心简单的动起来

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<style>
  * {
    margin: 0;
    padding: 0
  }
</style>

<body>
  <canvas></canvas>
  <script>
    const settings = {
      particles: {
        length: 500, // 最大粒子数
        duration: 2, // 粒子持续时间
        velocity: 100, // 粒子速度
        effect: -0.75, // play with this for a nice effect
        size: 30, // 粒子大小
      }
    }
    let canvas = document.querySelector('canvas')
    let ctx = canvas.getContext('2d')
    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
        let 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 image = (function () {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      canvas.width = settings.particles.size;
      canvas.height = settings.particles.size;
      
      // 帮助创建路径函数
      function to(t) {
        let 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;
      }
      // 创建路径
      ctx.beginPath();
      let t = -Math.PI;
      let point = to(t);
      // ctx.translate(10,10)  //移动心形
      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();
      // 添加填充
      ctx.fillStyle = '#ea80b0';
      ctx.fill();
      // 创建图像
      let image = new Image();
      image.src = canvas.toDataURL();
      return image;
    })();
    /*
     * 创建粒子
     */

    var Particle = (function () {
      function Particle() {
        // 创建实例
        this.position = new Point();
        this.velocity = new Point();
        this.acceleration = new Point();
        this.age = 0;
      }
      // 初始化位置 速度 加速度 时间
      Particle.prototype.initialize = function (x, y, dx, dy) {
        this.position.x = x;
        this.position.y = y;
        this.velocity.x = dx;
        this.velocity.y = dy;
        this.acceleration.x = dx * settings.particles.effect;
        this.acceleration.y = dy * settings.particles.effect;
        this.age = 0;
      };
      // 随时间变化
      Particle.prototype.update = function (deltaTime) {
        this.position.x += this.velocity.x * deltaTime;
        this.position.y += this.velocity.y * deltaTime;
        this.velocity.x += this.acceleration.x * deltaTime;
        this.velocity.y += this.acceleration.y * deltaTime;
        this.age += deltaTime;
      };
      // 在canvas上绘制
      Particle.prototype.draw = function (ctx, image) {
        function ease(t) {
          return (--t) * t * t + 1;
        }
        // var size = image.width * ease(this.age / settings.particles.duration);
        let size=30
        // 透明度
        ctx.globalAlpha = 1 - this.age / settings.particles.duration;
        // drawImage(img,x,y,width,height) 绘制一个图片以及图片位置大小;
        ctx.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);
      };
      return Particle;
    })();

    let newTime = new Date().getTime() / 1000
    function render(){
      requestAnimationFrame(render);
      deltaTime = new Date().getTime() / 1000-newTime;     
      canvas.width = canvas.clientWidth;
      canvas.height = canvas.clientHeight;
      let particle = new Particle()
      particle.initialize(100,0,10,10)
      particle.update(deltaTime)
      particle.draw(ctx, image)
    }
    render()    
  </script>
</body>

</html>
未命名.gif

很多动起来

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<style>
  * {
    margin: 0;
    padding: 0
  }

  html,
  body {
    height: 100%;
    padding: 0;
    margin: 0;
    background: #000;
  }

  canvas {
    width: 100%;
    height: 100%;
  }
</style>

<body>
  <canvas></canvas>
  <script>
    const settings = {
      particles: {
        length: 500, // 最大粒子数
        duration: 2, // 粒子持续时间
        velocity: 100, // 粒子速度
        effect: -0.75, // play with this for a nice effect
        size: 30, // 粒子大小
      }
    }

    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
        let 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 image = (function () {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      canvas.width = settings.particles.size;
      canvas.height = settings.particles.size;


      // 帮助创建路径函数
      function to(t) {
        let 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;
      }
      // 创建路径
      ctx.beginPath();
      let t = -Math.PI;
      let point = to(t);
      // ctx.translate(10,10)  //移动心形
      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();
      // 添加填充
      ctx.fillStyle = '#ea80b0';
      ctx.fill();
      // 创建图像
      let image = new Image();
      image.src = canvas.toDataURL();
      return image;
    })();


    /*
     * 创建粒子
     */

    let Particle = (function () {
      function Particle() {
        // 创建实例
        this.position = new Point();
        this.velocity = new Point();
        this.acceleration = new Point();
        this.age = 0;
      }
      // 初始化位置 速度 加速度 时间
      Particle.prototype.initialize = function (x, y, dx, dy) {
        this.position.x = x;
        this.position.y = y;
        this.velocity.x = dx;
        this.velocity.y = dy;
        this.acceleration.x = dx * settings.particles.effect;
        this.acceleration.y = dy * settings.particles.effect;
        this.age = 0;
      };
      // 随时间变化
      Particle.prototype.update = function (deltaTime) {
        this.position.x += this.velocity.x * deltaTime;
        this.position.y += this.velocity.y * deltaTime;
        this.velocity.x += this.acceleration.x * deltaTime;
        this.velocity.y += this.acceleration.y * deltaTime;
        this.age += deltaTime;
      };
      // 在canvas上绘制
      Particle.prototype.draw = function (ctx, image) {
        function ease(t) {
          return (--t) * t * t + 1;
        }
        let size = image.width * ease(this.age / settings.particles.duration);
        // 透明度
        ctx.globalAlpha = 1 - this.age / settings.particles.duration;
        // drawImage(img,x,y,width,height) 绘制一个图片以及图片位置大小;
        ctx.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);
      };
      return Particle;
    })();

    /*
     * 创建粒子池
     */
    var ParticlePool = (function () {
      var particles,
        firstActive = 0,
        firstFree = 0,
        duration = settings.particles.duration;

      function ParticlePool(length) {
        // 创建并填充粒子池
        particles = new Array(length);
        for (var i = 0; i < particles.length; i++)
          particles[i] = new Particle();
      }
      ParticlePool.prototype.add = function (x, y, dx, dy) {
        particles[firstFree].initialize(x, y, dx, dy);

        // 处理循环队列
        firstFree++;
        if (firstFree == particles.length) firstFree = 0;
        if (firstActive == firstFree) firstActive++;
        if (firstActive == particles.length) firstActive = 0;
      };
      ParticlePool.prototype.update = function (deltaTime) {
        var i;

        // 更新粒子
        if (firstActive < firstFree) {
          for (i = firstActive; i < firstFree; i++)
            particles[i].update(deltaTime);
        }
        if (firstFree < firstActive) {
          for (i = firstActive; i < particles.length; i++)
            particles[i].update(deltaTime);
          for (i = 0; i < firstFree; i++)
            particles[i].update(deltaTime);
        }

        // 删除不活跃粒子
        while (particles[firstActive].age >= duration && firstActive != firstFree) {
          firstActive++;
          if (firstActive == particles.length) firstActive = 0;
        }


      };
      ParticlePool.prototype.draw = function (ctx, image) {
        // 画出活动的粒子
        if (firstActive < firstFree) {
          for (i = firstActive; i < firstFree; i++)
            particles[i].draw(ctx, image);
        }
        if (firstFree < firstActive) {
          for (i = firstActive; i < particles.length; i++)
            particles[i].draw(ctx, image);
          for (i = 0; i < firstFree; i++)
            particles[i].draw(ctx, image);
        }
      };
      return ParticlePool;
    })();



    let canvas = document.querySelector('canvas')
    let ctx = canvas.getContext('2d')
    let particles = new ParticlePool(settings.particles.length)
    let particleRate = settings.particles.length / settings.particles.duration // particles/sec
    let time
    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
    (function render() {
      requestAnimationFrame(render);
      let newTime = new Date().getTime() / 1000
      let deltaTime = newTime - (time || newTime)
      time = newTime;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      let particle = new Particle()
      var amount = particleRate * deltaTime;
      for (var i = 0; i < amount; i++) {
        var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());
        var dir = pos.clone().length(settings.particles.velocity);
        particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
      }
      
      particles.update(deltaTime);
      particles.draw(ctx, image);

    })()      
  </script>
</body>

</html>
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,001评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,210评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,874评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,001评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,022评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,005评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,929评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,742评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,193评论 1 309
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,427评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,583评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,305评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,911评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,564评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,731评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,581评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,478评论 2 352