canvas绘制的直线动画

编程学习 2021-07-04 19:20www.dzhlxh.cn编程入门
本文主要分享了canvas绘制的直线动画的示例代码。具有很好的参考价值,狼蚁网站SEO优化跟着长沙网络推广一起来看下吧

话不多说,请看代码:

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>first line</title>
 <style type="text/css">
       body{
         background: #456E89;
       }
 .canvas {
 height: 300px;
 width: 300px; 
 margin: 0 auto;
 font-family: arial;
 }
 </style>
 </head>
 <body>
 <div class="canvas">
 <canvas id="cvs" width="300" height="300"></canvas>
 </div>
 <script type="text/javascript">
 var cvs = document.getElementById("cvs").getContext("2d");
 function Anim(opt) { //初始化值
 this.opt = opt;
 }
 //node 表示画布节点
 //staX 表示开始x坐标
 //staY 表示开始y坐标
 //len表示终点坐标,
 //timing表示运行的间隔时间, 
 //num表示坐标增长的大小 
 //direc表示判断绘制线条的方向,false表示X轴,ture表示Y轴
 //lw表示线宽的大小 
 //color 表示绘制线条颜色
 Anim.prototype.draw = function() { //绘制直线的线条
 var opt = this.opt; //设置对象的属性
 var adx = opt.staX;
 var ady = opt.staY;
 var that = {
  x: opt.staX,
  y: opt.staY
 };
 var Time = setInterval(function() {
  opt.direc //判断绘制方向
  ?
  opt.len > ady ? ady += opt.num : ady -= opt.num :
  opt.len > adx ? adx += opt.num : adx -= opt.num;
  if(adx == opt.len || ady == opt.len) { //停止循环
  clearInterval(Time);
  }
  opt.Node.beginPath(); // 开始绘制线条
  opt.Node.moveTo(that.x, that.y);
  opt.Node.lineTo(adx, ady);
  opt.Node.lineWidth = opt.lw || 1;
  opt.Node.strokeStyle = opt.color;
  opt.Node.stroke();
 }, opt.timing);
 };
 Anim.prototype.txt = function(opc) {//绘制文字 
 cvs.beginPath();
 cvs.fillStyle = "rgba(255,255,255,"+opc+")";
 cvs.font = "200px arial";
 cvs.fillText("L", 100, 200);
 };
 var line1 = new Anim({ //实例
 Node: cvs,
 color: "#fff",
 staX: 114,
 staY: 58,
 len: 134,
 timing: 50,
 num: 1,
 direc: false,
 lw: 2
 });
 line1.draw(); //执行绘制
 var line2 = new Anim({
 Node: cvs,
 color: "#fff",
 staX: 115,
 staY: 58,
 len: 200,
 timing: 20,
 num: 1,
 direc: true,
 lw: 2
 });
 line2.draw();
 var line3 = new Anim({
 Node: cvs,
 color: "#fff",
 staX: 133,
 staY: 184,
 len: 58,
 timing: 20,
 num: 1,
 direc: true,
 lw: 2
 });
 line3.draw();
 var line4 = new Anim({
 Node: cvs,
 color: "#fff",
 staX: 132,
 staY: 184,
 len: 203,
 timing: 35,
 num: 1,
 direc: false,
 lw: 2
 });
 line4.draw();
 var line5 = new Anim({
 Node: cvs,
 color: "#fff",
 staX: 203,
 staY: 199,
 len: 115,
 timing: 35,
 num: 1,
 direc: false,
 lw: 2
 });
 line5.draw();
 var line6 = new Anim({
 Node: cvs,
 color: "#fff",
 staX: 203,
 staY: 199,
 len: 184,
 timing: 50,
 num: 1,
 direc: true,
 lw: 2
 });
 line6.draw();
 var test = new Anim();//绘制文字实例
 setTimeout(function () {
 var num = 0;
 var times = setInterval(function () {
  num++;
  var t = num/100;
  if(t === 1){
  clearInterval(times);
  }
  test.txt(t);
 },50)
 },3000)
 </script>
 </body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持狼蚁SEO!

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板