Canvas基本动画-太阳系的动画

动画的基本步骤

一、清空canvas
除非接下来要画的内容会彻底充满canvas(例如背景图),不然你须要清空全部,最简单的方法是使用clearRect方法
二、保存canvas状态
若是你要改变一些会改变canvas状态的设置(样式,变形之类的),又要在每画一帧之时都是原始状态的话,你须要先保存一下
三、绘制动画图形
四、恢复canvas状态
若是已经保存了canvas的状态,能够先恢复它,而后重绘下一帧。javascript

下面是MDN网站关于Canvas基本的动画章节中的一个例子。是一个相对比较综合的例子,涉及到画布不少基础并经常使用的用法,包括canvas的如何使用图片,坐标原点的移动,画布的旋转,状态的保存与恢复等。html

<script>
var sun = new Image();
var moon = new Image();
var earth = new Image();

function init() {
    sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
    moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
    earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
    draw();
}

function draw() {
    var ctx = document.getElementById("canvas").getContext("2d");
    //在现有的画布内容后面绘制新的图形
    ctx.globalCompositeOperation = 'destination-over';
    ctx.clearRect(0, 0, 300, 300);

    ctx.fillStyle = "rgba(0,0,0,0.4)";
    ctx.strokeStyle = "rgba(0,153,255,0.4)";
    ctx.save();
    ctx.translate(150, 150);

    /*地球*/
    var time = new Date();
    ctx.rotate(((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds());
    //地球的背面
    ctx.translate(105, 0); //以ctx.translate(150,150);为基础
    ctx.fillRect(0, -12, 50, 24);
    //地球
    ctx.drawImage(earth, -12, -12)

    /*moon*/
    ctx.save(); //ctx.save(); 与下面的最近的ctx.restore();也能够不须要
    ctx.rotate(((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * time.getMilliseconds())
    ctx.translate(0, 28.5);
    ctx.drawImage(moon, -3.5, -3.5);
    ctx.restore();

    ctx.restore()

    /*地球的轨道*/
    ctx.beginPath();
    ctx.arc(150, 150, 105, 0, Math.PI * 2, false);
    ctx.stroke();

    /*太阳*/
    ctx.drawImage(sun, 0, 0, 300, 300);

    window.requestAnimationFrame(draw);
}
init()
</script>

查看动画效果java

相关文章
相关标签/搜索