[Canvas]Running Horse

时间:2025-03-19 00:07:43

下载地址:https://files.cnblogs.com/files/xiandedanteng/52-RunningHorse.rar,下载完毕后请使用Chrome浏览器打开Index.html查看。

图例:

[Canvas]Running Horse[Canvas]Running Horse

代码:

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>奔跑的马 19.3.3 13:20 horn19782016@163.com</title>
    </head>

     <body onload="draw()">
        <canvas id="myCanvus" width="120px" height="90px" style="border:1px dashed black;">
            出现文字表示你的浏览器不支持HTML5
        </canvas>
     </body>
</html>
<script type="text/javascript">
<!--
var ctx;// 绘图环境
var cds;// 从大图中取小图的坐标数组
var img;// 大图

function draw(){
    var canvas=document.getElementById('myCanvus');

    canvas.width=120;
    canvas.height=90;

    ctx=canvas.getContext('2d');

    img=new Image();
    img.src="runningHorse.jpg";

    // 图块坐标
    cds=[
        {'x':'0', 'y':'10','width':'120','height':'80'},
        {'x':'120','y':'10','width':'120','height':'80'},
        {'x':'240','y':'10','width':'120','height':'80'},
        {'x':'360','y':'10','width':'120','height':'80'},
        {'x':'480','y':'10','width':'120','height':'80'},

        {'x':'0', 'y':'100','width':'120','height':'80'},
        {'x':'120','y':'100','width':'120','height':'80'},
        {'x':'240','y':'100','width':'120','height':'80'},
        {'x':'360','y':'100','width':'120','height':'80'},
        {'x':'490','y':'100','width':'120','height':'80'},
   ];

    animate();
};

var index=0;
var i=0;

function animate(){
    ctx.clearRect(0,0,120,90);
    ctx.fillStyle = "rgb(137,201,3)";
    ctx.fillRect(0, 0, 120, 90);

    ctx.strokeStyle = "black";

    // 绘制地面
    ctx.beginPath();
    ctx.fillStyle = "black";
    ctx.moveTo(0, 80);
    ctx.lineTo(120,80);
    ctx.stroke();
    ctx.closePath();

    index++;
    if(index>100){
        index=0;
    }
    i=index % 10;

    // 截取一块图贴上
    ctx.drawImage(img,cds[i].x,cds[i].y,cds[i].width,cds[i].height,0,0,cds[i].width,cds[i].height);    

    setTimeout( function(){
        window.requestAnimationFrame(animate); /// 让浏览器自行决定帧速率
    }, 0.20 * 1000 );// 延时执行
}

//-->
</script>

2019年3月3日14点38分