HTML5 Canvas 龟羊赛跑

本文介绍了一个使用HTML5 Canvas实现的简单动画案例——龟羊赛跑。通过不断截取一张包含多个图块的图片,并将这些图块动态显示在Canvas上,实现了两个角色的跑步效果。代码中详细展示了如何定义图块坐标、设置动画速度以及循环播放动画。

从一张图上截取不同图块,动态显示在canvas上,形成赛跑的效果。完整代码图片下载请点击 https://files.cnblogs.com/files/xiandedanteng/turtleSheepRace.rar

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>龟羊赛跑</title>
    </head>

     <body onload="draw()">
        <canvas id="myCanvus" width="1000px" height="150px" style="border:1px dashed black;">
            出现文字表示你的浏览器不支持HTML5
        </canvas>
     </body>
</html>
<script type="text/javascript">
<!--
function draw(){
    var canvas=document.getElementById('myCanvus');
    
    canvas.width=1000;
    canvas.height=150;
    
    var context=canvas.getContext('2d');

    var img=new Image();
    img.src="walkingAnimals.jpg";
    
    //  乌龟图块坐标
    var turtleCds=[
        {'x':'10','y':'10','width':'110','height':'80'},
        {'x':'120','y':'10','width':'110','height':'80'},
        {'x':'230','y':'10','width':'110','height':'80'},
        {'x':'340','y':'10','width':'110','height':'80'},
    ];
    
    //  绵羊图块坐标
    var sheepCds=[
        {'x':'10','y':'100','width':'110','height':'100'},
        {'x':'120','y':'100','width':'100','height':'100'},
        {'x':'224','y':'100','width':'110','height':'100'},
        {'x':'330','y':'100','width':'110','height':'100'},
    ];

    loop=setInterval(function(){ run(context,img,turtleCds,sheepCds); }, 100);
};

var turtleSpeed=-80;
var sheepSpeed=-100;
var i=0;
function run(context,img,turtleCds,sheepCds){
    context.clearRect(0,0,1000,150);// clearScreen
    context.strokeStyle = "black";
    
    turtleSpeed++;
    if(turtleSpeed-80>1000){
        turtleSpeed=-80;
    }

    i=turtleSpeed % 4;
    
    sheepSpeed+=1.5;
    if(sheepSpeed-100>1000){
        sheepSpeed=-100;
    }
    
        
    // 截取一块图贴上
    context.drawImage(img,turtleCds[i].x,turtleCds[i].y,turtleCds[i].width,turtleCds[i].height,turtleSpeed,50,turtleCds[i].width,turtleCds[i].height);    
    context.drawImage(img,sheepCds[i].x,sheepCds[i].y,sheepCds[i].width,sheepCds[i].height,sheepSpeed,50,sheepCds[i].width,sheepCds[i].height);    
}

//-->
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值