博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Canvas学习]动画
阅读量:4657 次
发布时间:2019-06-09

本文共 2315 字,大约阅读时间需要 7 分钟。

学习目的:通过JavaScript操控<canvas>对象,实现交互动画。

动画的基本步骤

1. 清空canvas,使用clearRect方法

2. 保存canvas状态

3. 绘制动画图形

4. 恢复canvas状态

操控动画Controlling an animation

 setInterval(function, delay)

 setTimeout(function, delay)

 requestAnimationFrame(callback)

 

太阳系运动的小例子

<canvas id="canvas" width="300" height="300"></canvas>

<script type="text/javascript">
  var sun = new Image();
  var moon = new Image();
  var earth = new Image();
  var cvs = document.getElementById("canvas");
  /**
  * 创建三张图片并完成动画
  * @return {[type]} [description]
  */
  function init(){
    sun.src = "image/Canvas_sun.png";
    earth.src = "image/Canvas_earth.png";
    moon.src = "image/Canvas_moon.png";
    requestAnimationFrame(draw);
  }
  /**
  * 分别通过平移旋转来设置不同的canvas状态完成三张图片的绘制
  * @return {[type]} [description]
  */
  function draw(){
    if(cvs.getContext){
      var ctx = cvs.getContext("2d");
      ctx.globalCompositeOperation = "destination-over";
      //1. 清空clearRect
      ctx.clearRect(0,0,300,300);
      //2. 保存canvas状态
      ctx.fillStyle = "rgba(0,0,0,0,4)";
      ctx.strokeStyle = "rgba(0,153,255,0.4)";
      ctx.save();
      ctx.translate(150,150);//sun图片大小为300*300
      //3. 绘制图片
      var time = new Date();
      //绘制地球
      ctx.rotate((2*Math.PI/60)*time.getSeconds()+(2*Math.PI/60000)*time.getMilliseconds());//1分钟=60秒,设置地球围绕太阳的旋转周期为1min
      ctx.translate(105, 0);//地球运行轨迹半径为105
      ctx.fillRect(0,-12,50,24);//地球阴影
      ctx.drawImage(earth, -12, -12);//地球图片大小为24*24
      ctx.beginPath();
      ctx.arc(0,0,28.5,0,Math.PI*2,false);
      ctx.closePath();
      ctx.stroke();

      ctx.save();

      //绘制月球//此时canvas状态为默认状态
      ctx.rotate((2*Math.PI/60)*time.getSeconds()+(2*Math.PI/60000)*time.getMilliseconds());
      ctx.translate(0,28.5);//月球的运行轨迹半径为28.5
      ctx.drawImage(moon, -3.5, -3.5);//月球图片大小为7*7

      ctx.restore();

      ctx.restore();
      //最初的canvas状态
      ctx.beginPath();
      ctx.arc(150,150,105,0,Math.PI*2,false);
      ctx.closePath();
      ctx.stroke();
      ctx.drawImage(sun, 0, 0, 300, 300);

      requestAnimationFrame(draw);

    }
  }
  init();
</script>

 

canvas绘制动画时钟

绘制时钟的方法有很多,分别介绍下不同的思路:

1. 利用canvas来绘制动画时钟,通过平移旋转来实现线段和圆的绘制

2. 利用HTML+CSS3来绘制动画时钟,也是通过CSS3的变形属性来实现线段和圆的绘制

这两种实现方法都需要通过JavaScript来确定当前的时间点,从而确定各个指针的初始位置。

 

绘制小球

加入控制元素,如物理碰撞检测等

转载于:https://www.cnblogs.com/joyjoe/p/6107671.html

你可能感兴趣的文章
dp练习
查看>>
[javascript]9宫格拖拽拼图游戏 puzzle
查看>>
Entity Framework底层操作封装(3)
查看>>
InputStream 转换 InputStreamReader再转换BufferedReader
查看>>
在线程池中的使用spring aop事务增强
查看>>
javascript相关知识
查看>>
数组对象去重
查看>>
你未必知道的12个JavaScript技巧
查看>>
mysql的基本操作命令
查看>>
微信小程序---数据缓存
查看>>
Python网页正文转换语音文件的操作方法
查看>>
常用SQL查询语句
查看>>
Redis Windows版安装详解
查看>>
linux后台运行python程序 nohup
查看>>
吴裕雄--天生自然 高等数学学习:对面积的曲面积分
查看>>
css
查看>>
消除头文件
查看>>
Android中数据文件解析(Json解析)
查看>>
自定义seekBar设置进度条背景图片
查看>>
java容器类1:Collection,List,ArrayList,LinkedList深入解读
查看>>