动画原理——加载图片
书籍名称:HTML5-Animation-with-JavaScript
书籍源码:https://github.com/lamberta/html5-animation
1.实时加载图片
要实现实时加载图片,先创建一个图片对象设置它的src为URL地址。利用onload方法设置当图片对象加载完成执行回调函数。
在下面这个例子中,我们在图片加载完成后实时插入一张图片。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load Image</title>
<link rel="stylesheet" href="../include/style.css">
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
image = new Image();
image.src = "./assets/picture.jpg";
image.onload = function() {
context.drawImage(image, 0, 0);
};
};
</script>
</body>
</html>
2.插入页面中的图片元素
在页面加载的时候加载图片隐藏,使用DOM获取图片元素,然后调用canvas。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Embed Image</title>
<link rel="stylesheet" href="../include/style.css">
<style>
#picture {
display: none;
}
</style>
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="400" height="400"></canvas>
<img id="picture" src="./assets/picture.jpg">
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
image = document.getElementById('picture');
context.drawImage(image, 0, 0);
};
</script>
</body>
</html>
3.使用视频元素
和画静态动画一样,在一个时间点,只有一个画面。需要用到requestAnimationFrame
而插入页面中的视频元素和插入图片一样,下面看代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Video Frames</title>
<link rel="stylesheet" href="../include/style.css">
<style>
#movieclip {
display: none;
}
</style>
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="600" height="360"></canvas>
<aside>Video file may take a moment to load.</aside>
<video id="movieclip" width="640" height="360" autoplay>
<source src="./assets/movieclip.mp4" type="video/mp4"/>
<source src="./assets/movieclip.webm" type="video/webm"/>
<source src="./assets/movieclip.ogv" type="video/ogg"/>
</video>
<script src="../include/utils.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
video = document.getElementById('movieclip');
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.drawImage(video, 0, 0);
}());
};
</script>
</body>
</html>
浙公网安备 33010602011771号