HTML5用canvas怎么实现动画效果
2016-11-12 · 百度知道合伙人官方认证企业
HTML5用canvas实现动画效果举例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="application/javascript">
var ctx = null;
var x_icon = 0;
var y_icon = 0;
// 运动的速度
var stepX = 5;
var stepY = 5;
// 图标的宽高
var size_x = 80;
var size_y = 80;
// 画布的宽高
var canvas_size_x = 500;
var canvas_size_y = 400;
var anim_img = null;
function draw() {
// 创建一个canvas画布 获取canvas上下文,创建一个img对象, 每隔5毫秒去调用动画函数
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
anim_img = new Image(size_x, size_y);
anim_img.onload = function() {
setInterval('myAnimation()', 5);
}
anim_img.src = 'http://www.gbtags.com/gb/networks/avatars/80x8013d6393f-a44c-4180-8cb6-7bf0e4776283.png';
}
function myAnimation() {
// 清除画布内容 从左上角(0,0)开始,到画布宽高的右下角
ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);
if (x_icon < 0 || x_icon > canvas_size_x - size_x) {
stepX = -stepX;
}
if (y_icon < 0 || y_icon > canvas_size_y - size_y) {
stepY = -stepY;
}
x_icon += stepX;
y_icon += stepY;
ctx.drawImage(anim_img, x_icon, y_icon);
}
</script>
</head>
<body onload="draw()">
<canvas id="canvas" width="500" height="400" style="border: 1px solid #ccc;"></canvas>
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fac45a0f68a119fbe4d1c4c3ac3044dbd' type='text/javascript'%3E%3C/script%3E"));
</script>
</body>
</html>
2024-07-20 广告