[Canvas]飞机飞越河谷(背景向下平滑移动)

点击此处下载代码并用Chrome浏览器打开观看。

图例:

代码:

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>动态背景3 19.3.4 12:43 by:逆火狂飙 horn19782016@163.com</title>
     
     <style>
     #canvas{
        background:#ffffff;
        cursor:pointer;
        margin-left:10px;
        margin-top:10px;
        -webkit-box-shadow:3px 3px 6px rgba(0,0,0,0.5);
        -moz-box-shadow:3px 3px 6px rgba(0,0,0,0.5);
        box-shadow:3px 3px 6px rgba(0,0,0,0.5);
     }
     
     #controls{
        margin-top:10px;
        margin-left:15px;
     }
     </style>
     
    </head>

     <body onload="init()">
        <div id="controls">
            <input id='animateBtn' type='button' value='运动'/>
        </div>
     
        <canvas id="canvas" width="1200px" height="562px" >
            出现文字表示你的浏览器不支持HTML5
        </canvas>
     </body>
</html>
<script type="text/javascript">
<!--
var paused=true;
animateBtn.onclick=function(e){
    paused=! paused;
    
    if(paused){
        animateBtn.value="运动";
    }else{    
        animateBtn.value="暂停";
        window.requestAnimationFrame(animate); 
    }
}

var ctx;// 绘图环境
var bg;// 背景
var bgOffset;
var bgVelocity;
var lastTime=0;
var fps=0;
var plane;

function init(){
    bg=new Image();
    bg.src="riverBg.jpg";
    bg.width=104;
    bg.height=156;
    
    plane=new Image();
    plane.src="yellowPlane.png";
    
    // init Canvas
    var canvas=document.getElementById('canvas');
    canvas.width=bg.width*4;
    canvas.height=bg.height*4;
    ctx=canvas.getContext('2d');

    bgOffset=0;
    bgVelocity=40;
    
    lastTime=+new Date;
};

function update(){

}


function draw(){
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);

    fps=calculateFps(new Date);
    bgOffset=bgOffset<bg.height?bgOffset+bgVelocity/fps:0;
    ctx.drawImage(bg,0,bg.height-bgOffset,bg.width,bgOffset,0,0,ctx.canvas.width,4*bgOffset);
    ctx.drawImage(bg,0,0,bg.width,bg.height-bgOffset,0,4*bgOffset,canvas.width,canvas.height-4*bgOffset);
    
    ctx.drawImage(plane,ctx.canvas.width/2-50,canvas.height-100);
}

function calculateFps(now){
    var retval=1000/(now-lastTime);
    lastTime=now;
    console.log("fps",retval)
    return retval;
}

function animate(){
    if(!paused){
        update();
        draw();
    }
    
    window.requestAnimationFrame(animate);
}
//-->
</script>

以上部分Title没改,和之前的例子可能会重复,见谅。

2019年3月12日10点55分

http://vt1.doubanio.com/201903121827/e4eb397bc8878e8e9c94e47fa2b1cc4b/view/movie/M/402410917.mp4

原文地址:https://www.cnblogs.com/heyang78/p/10515279.html