HTML5:七天学会基础动画网页7
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
在HTML5中,创建一个基础的动画页面,可以使用<canvas>
元素和JavaScript来绘制动画。以下是一个简单的示例,演示如何使用HTML5 Canvas API创建一个简单的动画:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 基础动画示例</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var x = 50;
var y = 50;
var radius = 20;
var color = 'blue';
var dx = 2;
function drawCircle() {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawCircle();
x += dx;
if (x > canvas.width - radius || x < radius) {
dx = -dx;
}
window.requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
这段代码创建了一个<canvas>
元素,并在其上绘制了一个蓝色的圆。通过requestAnimationFrame
方法,每帧都会重绘圆的位置,并且如果圆碰到边界就会反弹。这个示例演示了如何使用HTML5的Canvas API进行简单的动画制作。
评论已关闭