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 相关文章推荐
纯CSS绘制漂亮的圆形图案效果
May 07 HTML / CSS
CSS3 input框的实现代码类似Google登录的动画效果
Aug 04 HTML / CSS
Html5移动端获奖无缝滚动动画实现示例
Jun 25 HTML / CSS
HTML5之SVG 2D入门3—文本与图像及渲染文本介绍
Jan 30 HTML / CSS
HTML5 UTF-8 中文乱码的解决方法
Nov 18 HTML / CSS
html5的自定义data-*属性与jquery的data()方法的使用
Jul 02 HTML / CSS
HTML5到底会有什么发展?HTML5的前景展望
Jul 07 HTML / CSS
详解HTML5中ol标签的用法
Sep 08 HTML / CSS
利用Storage Event实现页面间通信的示例代码
Jul 26 HTML / CSS
原生canvas制作画图小工具的踩坑和爬坑
Jun 09 HTML / CSS
h5页面背景图很长要有滚动条滑动效果的实现
Jan 27 HTML / CSS
CSS3 制作精美的定价表
Apr 06 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 session机制
2011/07/17 PHP
PHP批量检测并去除文件BOM头代码实例
2014/05/08 PHP
php中substr()函数参数说明及用法实例
2014/11/15 PHP
php 生成签名及验证签名详解
2016/10/26 PHP
jQuery点击后一组图片左右滑动的实现代码
2012/08/16 Javascript
location对象的属性和方法应用(解析URL)
2013/04/12 Javascript
js获取input标签的输入值实现代码
2013/08/05 Javascript
使用cluster 将自己的Node服务器扩展为多线程服务器
2014/11/10 Javascript
js+flash实现的5图变换效果广告代码(附演示与demo源码下载)
2016/04/01 Javascript
Javascript中浏览器窗口的基本操作总结
2016/08/18 Javascript
详解AngularJS如何实现跨域请求
2016/08/22 Javascript
jQuery插件zTree实现的多选树效果示例
2017/03/08 Javascript
vue解决一个方法同时发送多个请求的问题
2018/09/25 Javascript
微信小程序下拉菜单效果的实例代码
2019/05/14 Javascript
JavaScript内置对象math,global功能与用法实例分析
2019/06/10 Javascript
在layui中使用form表单监听ajax异步验证注册的实例
2019/09/03 Javascript
vue实现修改图片后实时更新
2019/11/14 Javascript
npm qs模块使用详解
2020/02/07 Javascript
详解Vue3 Composition API中的提取和重用逻辑
2020/04/29 Javascript
JS中循环遍历数组的四种方式总结
2021/01/23 Javascript
[02:08]2014DOTA2国际邀请赛 430专访:力争取得小组前二
2014/07/11 DOTA
[44:58]2018DOTA2亚洲邀请赛 4.5 淘汰赛 LGD vs Liquid 第二场
2018/04/06 DOTA
python实现的简单猜数字游戏
2015/04/04 Python
python实现感知器算法详解
2017/12/19 Python
Python简单生成随机姓名的方法示例
2017/12/27 Python
python列表的增删改查实例代码
2018/01/30 Python
实例讲解Python3中abs()函数
2019/02/19 Python
Python整数对象实现原理详解
2019/07/01 Python
python实现定时发送邮件到指定邮箱
2020/12/23 Python
Ubuntu20.04环境安装tensorflow2的方法步骤
2021/01/29 Python
一款利用纯css3实现的360度翻转按钮的实例教程
2014/11/05 HTML / CSS
观看《周恩来的四个昼夜》思想汇报
2014/09/12 职场文书
寒山寺导游词
2015/02/03 职场文书
vscode中使用npm安装babel的方法
2021/08/02 Javascript
怎么禁用Windows 11快照布局? win11不使用快照布局的技巧
2021/11/21 数码科技
MySQL性能指标TPS+QPS+IOPS压测
2022/08/05 MySQL