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的@media来编写响应式的页面
Nov 01 HTML / CSS
CSS类名支持中文命名的示例
Apr 04 HTML / CSS
使用CSS3设计地图上的雷达定位提示效果
Apr 05 HTML / CSS
canvas之万花筒效果的简单实现(推荐)
Aug 16 HTML / CSS
CSS3 实现的加载动画
Dec 07 HTML / CSS
利用简洁的图片预加载组件提升html5移动页面的用户体验
Mar 11 HTML / CSS
你可能不熟练的十个前端HTML5经典面试题
Jul 03 HTML / CSS
html5 Canvas画图教程(1)—画图的基本常识
Jan 09 HTML / CSS
HTML5 video 视频标签使用介绍
Feb 03 HTML / CSS
深入了解canvas在移动端绘制模糊的问题解决
Apr 30 HTML / CSS
amaze ui 的使用详细教程
Aug 19 HTML / CSS
css中:last-child不生效的解决方法
Aug 05 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
laravel5.4生成验证码的实例讲解
2017/08/05 PHP
php中yar框架实例用法讲解
2020/12/27 PHP
Javascript 写的简单进度条控件
2008/01/22 Javascript
js利用Array.splice实现Array的insert/remove
2009/01/13 Javascript
jQuery get和post 方法传值注意事项
2009/11/03 Javascript
基于jQuery的图片剪切插件
2011/08/03 Javascript
jQuery中实现动画效果的基本操作介绍
2013/04/16 Javascript
jquery简单的拖动效果实现原理及示例
2013/07/26 Javascript
使用jquery实现IE下按backspace相当于返回操作
2014/03/18 Javascript
JS中取二维数组中最大值的方法汇总
2016/04/17 Javascript
JavaScript“尽快失败”的原则实例详解
2016/10/08 Javascript
JS正则匹配中文的方法示例
2017/01/06 Javascript
jQuery中的deferred对象和extend方法详解
2017/05/08 jQuery
vue实现表格增删改查效果的实例代码
2017/07/18 Javascript
使用vue.js在页面内组件监听scroll事件的方法
2018/09/11 Javascript
vue路由事件beforeRouteLeave及组件内定时器的清除方法
2018/09/29 Javascript
JavaScript中七种流行的开源机器学习框架
2018/10/11 Javascript
NodeJS加密解密及node-rsa加密解密用法详解
2018/10/12 NodeJs
JS实现随机生成10个手机号的方法示例
2018/12/07 Javascript
IE浏览器下JS脚本提交表单后,不能自动提示问题解决方法
2019/06/04 Javascript
把MySQL表结构映射为Python中的对象的教程
2015/04/07 Python
使用Python向C语言的链接库传递数组、结构体、指针类型的数据
2019/01/29 Python
解决python写入带有中文的字符到文件错误的问题
2019/01/31 Python
python脚本当作Linux中的服务启动实现方法
2019/06/28 Python
Python StringIO及BytesIO包使用方法解析
2020/06/15 Python
Python利用imshow制作自定义渐变填充柱状图(colorbar)
2020/12/10 Python
python中类与对象之间的关系详解
2020/12/16 Python
解决selenium+Headless Chrome实现不弹出浏览器自动化登录的问题
2021/01/09 Python
CSS3 calc()会计算属性详解
2018/02/27 HTML / CSS
html5触摸事件判断滑动方向的实现
2018/06/05 HTML / CSS
全球性的在线时尚男装零售商:boohooMAN
2016/12/17 全球购物
高中生活自我鉴定
2014/01/18 职场文书
关于母亲节的感言
2014/02/04 职场文书
家长评语和期望
2014/02/10 职场文书
工作表扬信
2015/01/17 职场文书
2016学习雷锋精神活动倡议书
2015/04/27 职场文书