点击这里可以看动画效果:
http://www.108js.com/article/article3/zip1/30229/Test.html
效果图:
代码:
<html>
<head>
<meta charset="gbk">
<title>HTML5 绕四边运动的文字</title>
<link type="text/css" rel="stylesheet" href="css/main.css" />
</head>
<body>
<div id="wrap">
<canvas width="600" height="200" id="myCanvas"></canvas>
</div>
<div id="msg1"></div>
</body>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var width=canvas.width;
var height=canvas.height;
var point_size=25;
var message="绕四边运动的文字!";
var char_array=[];
var offset_x=[];
var offset_y=[];
var y1=height-point_size;
var x1=point_size;
var loop;
var dir=["up","right","down","left"];
var index=0;
function init()
{
length=message.length;
char_array=message.split("")
loop = setInterval(function () {
update(dir[index]);
paint();
}, 500);
}
function update(direct)
{
switch(direct){
case "up":
var j=-1;
for(var i=0;i<length;i++){
if(y1+i*point_size>height-point_size){
if(j<0)
j=i;
offset_y[i]=height-point_size;
offset_x[i]=(i-j+2)*point_size;
}
else{
offset_y[i]=y1+i*point_size;
offset_x[i]=point_size;
}
}
if(y1>point_size) y1-=point_size;
else index++;
break;
case "right" :
j=-1;
for(i=0;i<length;i++){
if(x1-i*point_size<point_size*2){
if(j<0)
j=i;
offset_y[i]=(i-j+1)*point_size;
offset_x[i]=point_size;
}
else{
offset_y[i]=point_size;
offset_x[i]=x1-i*point_size;
}
}
if(x1<width-point_size)
x1+=point_size;
else
index++;
break;
case "down":
j=-1;
for( i=0;i<length;i++){
if(y1-i*point_size<point_size){
if(j<0)
j=i;
offset_y[i]=point_size;
offset_x[i]=width-(i-j+2)*point_size;
}
else{
offset_y[i]=y1-i*point_size;
offset_x[i]=width-point_size;
}
}
if(y1<height-point_size) y1+=point_size;
else
index++;
break;
case "left":
j=-1;
for(i=0;i<length;i++){
if(x1+i*point_size>width-point_size*2){
if(j<0)
j=i;
offset_y[i]=height-(i-j+1)*point_size;
offset_x[i]=width-point_size;
}
else{
offset_y[i]=height-point_size;
offset_x[i]=x1+i*point_size;
}
}
if(x1>point_size) x1-=point_size;
else{
index=0;
y1=height-point_size;
x1=point_size;
}
break;
}
}
function paint(){
context.font = '25px Palatino';
context.clearRect(0,0,width,80);
context.clearRect(width-80,0,80,height);
context.clearRect(0,height-80,width,80);
context.clearRect(0,0,80,height);
context.strokeStyle = 'blue';
for(var i=0;i<message.length;i++){
context.strokeText(char_array[i],offset_x[i],offset_y[i]);
context.fillText(char_array[i],offset_x[i],offset_y[i]);
}
context.font = '100px Palatino';
context.strokeText("HTML5 动画",width/10,2*height/3);
}
window.onload=init;
</script>
</html>
全部代码请下载。
热情奉献:HTML5 Canvas绘图与动画学习59例源码
http://www.108js.com/example.html