canvas简单连线动画的实现代码


Posted in HTML / CSS onFebruary 04, 2020

前言:canvas动画入门系列之简单连线动画。虽然简单,但连线动画应用场景还挺多,因此做了个小demo,一通百通。

step1:绘制点

首先创建个标签<canvas id="canvas"></canvas>
设置几个点的坐标

const points = [
        [200, 100], //上
        [300, 200], //右
        [100, 200], //左
        [200, 100], //上
        [200, 300], //下
        [100, 200], //左
        [300, 200], //右
        [200, 300]
      ];
      const canvas = document.querySelector("canvas");
      const ctx = canvas.getContext("2d");

然后把点给画出来

canvas简单连线动画的实现代码

points.forEach(([x, y]) => {
          drawDot(x, y);
        });
function drawDot(x1, y1, r) {
          ctx.save();
          ctx.beginPath(); //不写会和线连起来
          ctx.fillStyle = "red";
          //绘制成矩形
          ctx.arc(x1, y1, r ? r : 2, 0, 2 * Math.PI);
          ctx.fill();
          ctx.restore();
        }

step2:绘制线条

我们封装一个方法,传入起点终点,绘制一根线条

function drawLine(x1, y1, x2, y2) {
          ctx.save();
          ctx.beginPath(); //不写每次都会重绘上次的线
          ctx.lineCap = "round";
          ctx.lineJoin = "round";
          var grd = ctx.createLinearGradient(x1, y1, x2, y2);

          ctx.moveTo(x1, y1);
          ctx.lineTo(x2, y2);
          ctx.closePath();
          ctx.strokeStyle = "rgba(255,255,255,1)";
          ctx.stroke();
          ctx.restore();
        }

step3:线条动画

这里面需要计算两点之间的斜率,然后x坐标每次挪动±1单位,已知斜率和x偏移,即可计算出y的偏移。值得注意的是,这个坐标系和数学中的xy坐标系有点不一样,y轴是反的。然后可以引入额外的参数speed控制速度

function lineMove(points) {
          if (points.length < 2) {
              
            return;
          }
          const [[x1, y1], [x2, y2]] = points;
          let dx = x2 - x1;
          let dy = y2 - y1;
          if (Math.abs(dx) < 1 && Math.abs(dy) < 1) {
            points = points.slice(1);
            lineMove(points);
            return;
          }
          let x = x1,
            y = y1; //线条绘制过程中的终点
          if (dx === 0) {
            (x = x2), (y += (speed * dy) / Math.abs(dy));
          } else if (dy === 0) {
            x += (speed * dx) / Math.abs(dx);
            y = y2;
          } else if (Math.abs(dx) >= 1) {
            let rate = dy / dx;
            x += (speed * dx) / Math.abs(dx);
            y += (speed * rate * dx) / Math.abs(dx);
          }
          drawLine(x1, y1, x, y);
          points[0] = [x, y];
          window.requestAnimationFrame(function() {
            lineMove(points);
          });
        }

主要代码就这么多,先看效果

canvas简单连线动画的实现代码

完整代码

<!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>canvas-连线动画</title>
</head>

<body>
  <canvas id="canvas" width="400" height="400"></canvas>
  <script>
    //起点:10,20 终点:150,200
    const points = [
      [200, 100], //上
      [300, 200], //右
      [100, 200], //左
      [200, 100], //上
      [200, 300], //下
      [100, 200], //左
      [300, 200], //右
      [200, 300]
    ];
    const canvas = document.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    // const img = new Image();
    const speed = 10; //速度
    // img.onload = function() {
    // canvas.width = img.width;
    // canvas.height = img.height;
    animate(ctx);
    // };

    // img.src = "./imgs/demo.png";
    function animate(ctx) {
      // ctx.drawImage(img, 0, 0);
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      points.forEach(([x, y]) => {
        drawDot(x, y);
      });
      lineMove(points);
    }
    function lineMove(points) {
      if (points.length < 2) {
        return;
      }
      const [[x1, y1], [x2, y2]] = points;
      let dx = x2 - x1;
      let dy = y2 - y1;
      if (Math.abs(dx) < 1 && Math.abs(dy) < 1) {
        points = points.slice(1);
        lineMove(points);
        return;
      }
      let x = x1,
        y = y1; //线条绘制过程中的终点
      if (dx === 0) {
        (x = x2), (y += (speed * dy) / Math.abs(dy));
      } else if (dy === 0) {
        x += (speed * dx) / Math.abs(dx);
        y = y2;
      } else if (Math.abs(dx) >= 1) {
        let rate = dy / dx;
        x += (speed * dx) / Math.abs(dx);
        y += (speed * rate * dx) / Math.abs(dx);
      }
      drawLine(x1, y1, x, y);
      points[0] = [x, y];
      window.requestAnimationFrame(function () {
        lineMove(points);
      });
    }

    function drawLine(x1, y1, x2, y2) {
      ctx.save();
      ctx.beginPath(); //不写每次都会重绘上次的线
      ctx.lineCap = "round";
      ctx.lineJoin = "round";
      var grd = ctx.createLinearGradient(x1, y1, x2, y2);

      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.closePath();
      ctx.strokeStyle = "rgba(255,255,255,1)";
      ctx.stroke();
      ctx.restore();
    }

    function drawDot(x1, y1, r) {
      ctx.save();
      ctx.beginPath(); //不写会和线连起来
      ctx.fillStyle = "red";
      //绘制成矩形
      ctx.arc(x1, y1, r ? r : 2, 0, 2 * Math.PI);
      ctx.fill();
      ctx.restore();
    }
  </script>
</body>

</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

HTML / CSS 相关文章推荐
一款基于css3的列表toggle特效实例教程
Jan 04 HTML / CSS
纯CSS3绘制打火机动画火焰效果
Jul 18 HTML / CSS
利用CSS3制作简单的3d半透明立方体图片展示
Mar 25 HTML / CSS
浅谈CSS3 动画卡顿解决方案
Jan 02 HTML / CSS
用HTML5制作一个简单的桌球游戏的教程
May 12 HTML / CSS
详解HTML5 Canvas绘制不规则图形时的非零环绕原则
Mar 21 HTML / CSS
详解移动端HTML5页面端去掉input输入框的白色背景和边框(兼容Android和ios)
Dec 15 HTML / CSS
html5组织内容_动力节点Java学院整理
Jul 10 HTML / CSS
HTML5 移动页面自适应手机屏幕四类方法总结
Aug 17 HTML / CSS
html5拖拽应用记录及注意点
May 27 HTML / CSS
CSS3实现指纹特效代码
Mar 17 HTML / CSS
基于CSS制作创意端午节专属加载特效
Jun 01 HTML / CSS
html5手机键盘弹出收起的处理
Jan 20 #HTML / CSS
canvas实现烟花的示例代码
Jan 16 #HTML / CSS
使用iframe+postMessage实现页面跨域通信的示例代码
Jan 14 #HTML / CSS
Html5跳转到APP指定页面的实现
Jan 14 #HTML / CSS
html5自动播放mov格式视频的实例代码
Jan 14 #HTML / CSS
html5响应式开发自动计算fontSize的方法
Jan 13 #HTML / CSS
html5 制作地图当前定位箭头的方法示例
Jan 10 #HTML / CSS
You might like
php实现字符串首字母大写和单词首字母大写的方法
2015/03/14 PHP
使用PHP+AJAX让WordPress动态加载文章的教程
2015/12/11 PHP
javascript document.execCommand() 常用解析
2009/12/14 Javascript
关于锚点跳转及jQuery下相关操作与插件
2012/10/01 Javascript
返回顶部按钮响应滚动且动态显示与隐藏
2014/10/14 Javascript
jquery分割字符串的方法
2015/06/24 Javascript
JS组件系列之Bootstrap Icon图标选择组件
2016/01/28 Javascript
JavaScript判断DIV内容是否为空的方法
2016/01/29 Javascript
JavaScript实现简单的拖动效果
2016/07/02 Javascript
Bootstrap 最常用的JS插件系列总结(图片轮播、标签切换等)
2016/07/14 Javascript
JS字符串false转boolean的方法(推荐)
2017/03/08 Javascript
基于jQuery实现一个marquee无缝滚动的插件
2017/03/09 Javascript
用js屏蔽被http劫持的浮动广告实现方法
2017/08/10 Javascript
openlayers实现地图弹窗
2020/09/25 Javascript
Python中利用sqrt()方法进行平方根计算的教程
2015/05/15 Python
简单实现python爬虫功能
2015/12/31 Python
python统计多维数组的行数和列数实例
2018/06/23 Python
python定时复制远程文件夹中所有文件
2019/04/30 Python
python ctypes库2_指定参数类型和返回类型详解
2019/11/19 Python
Django多进程滚动日志问题解决方案
2019/12/17 Python
image-set实现Retina屏幕下图片显示详细介绍
2012/12/24 HTML / CSS
生物有机护肤品:Aurelia Probiotic Skincare
2018/01/31 全球购物
英国在线汽车和面包车零件商店:Car Parts 4 Less
2018/08/15 全球购物
联想C++笔试题
2012/06/13 面试题
东方通信股份有限公司VC面试题
2014/08/27 面试题
中软国际Java程序员机试题
2012/08/19 面试题
大二学期个人自我评价
2014/01/13 职场文书
小学红领巾中秋节广播稿
2014/01/13 职场文书
监察建议书范文
2014/03/12 职场文书
学校党委副书记个人对照检查材料思想汇报
2014/09/28 职场文书
2015年百日安全活动总结
2015/03/26 职场文书
2015年学校工作总结范文
2015/04/20 职场文书
2016党校学习心得体会
2016/01/07 职场文书
党风廉政教育心得体会2016
2016/01/22 职场文书
Python爬虫数据的分类及json数据使用小结
2021/03/29 Python
浅谈Python魔法方法
2021/06/28 Java/Android