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 3D位移translate效果实例介绍
May 03 HTML / CSS
CSS教程:CSS3圆角属性
Apr 02 HTML / CSS
CSS3条纹背景制作的实战攻略
May 31 HTML / CSS
CSS3实现可爱的小黄人动画
Jul 11 HTML / CSS
html5指南-1.html5全局属性(html5 global attributes)深入理解
Jan 07 HTML / CSS
HTML5 Canvas画线技巧——实现绘制一个像素宽的细线
Aug 02 HTML / CSS
解决Firefox下不支持outerHTML问题代码分享
Jun 04 HTML / CSS
针对HTML5的Web Worker使用攻略
Jul 12 HTML / CSS
浅析移动设备HTML5页面布局
Dec 01 HTML / CSS
详解移动端html5页面长按实现高亮全选文本内容的兼容解决方案
Dec 03 HTML / CSS
html2canvas截图空白问题的解决
Mar 24 HTML / CSS
HTML5 body设置自适应全屏
May 07 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
win2003服务器使用WPS的COM组件的一些问题解决方法
2012/01/11 PHP
使用php 获取时间今天明天昨天时间戳的详解
2013/06/20 PHP
php中的静态变量的基本用法
2014/03/20 PHP
浅析PHP文件下载原理
2014/12/25 PHP
php检查字符串中是否有外链的方法
2015/07/29 PHP
探究Laravel使用env函数读取环境变量为null的问题
2016/12/06 PHP
PHP中常用的魔术方法
2017/04/28 PHP
针对PHP开发安全问题的相关总结
2019/03/22 PHP
十个优秀的Ajax/Javascript实例网站收集
2010/03/31 Javascript
Jquery中Ajax 缓存带来的影响的解决方法
2011/05/19 Javascript
JavaScript常用对象的方法和属性小结
2012/01/24 Javascript
jquery如何把参数列严格转换成数组实现思路
2013/04/01 Javascript
js计算字符串长度包含的中文是utf8格式
2013/10/15 Javascript
前台js调用后台方法示例
2013/12/02 Javascript
node.js中的path.dirname方法使用说明
2014/12/09 Javascript
JS实现的另类手风琴效果网页内容切换代码
2015/09/08 Javascript
jQuery实现的分子运动小球碰撞效果
2016/01/27 Javascript
关于Bootstrap弹出框无法调用问题的解决办法
2016/03/10 Javascript
第七篇Bootstrap表单布局实例代码详解(三种表单布局)
2016/06/21 Javascript
微信小程序 数据交互与渲染实例详解
2017/01/21 Javascript
Vue报错:Uncaught TypeError: Cannot assign to read only property’exports‘ of object’#‘的解决方法
2017/06/17 Javascript
微信小程序block的使用教程
2018/04/01 Javascript
vue-router 起步步骤详解
2019/03/26 Javascript
JS html事件冒泡和事件捕获操作示例
2019/05/01 Javascript
基于vue的video播放器的实现示例
2021/02/19 Vue.js
[01:00]一分钟回顾2018DOTA2亚洲邀请赛现场活动
2018/04/07 DOTA
Selenium控制浏览器常见操作示例
2018/08/13 Python
记一次python 内存泄漏问题及解决过程
2018/11/29 Python
Python3 文章标题关键字提取的例子
2019/08/26 Python
Python @property原理解析和用法实例
2020/02/11 Python
python查询MySQL将数据写入Excel
2020/10/29 Python
Notino希腊:购买香水和美容产品
2019/07/25 全球购物
会计应届生的自荐信
2013/12/13 职场文书
高中语文课后反思
2014/04/27 职场文书
群众路线剖析材料(四风)
2014/11/05 职场文书
pandas中DataFrame数据合并连接(merge、join、concat)
2021/05/30 Python