[Canvas]动态背景

欲查看动态效果请点击下载代码再用Chrome或Firefox打开index.html

图例:

代码:

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>动态背景 19.3.4 10:21 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="1024px" height="576px" >
            出现文字表示你的浏览器不支持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;

function init(){
    // init Canvas
    var canvas=document.getElementById('canvas');
    canvas.width=1024;
    canvas.height=576;
    ctx=canvas.getContext('2d');
    
    // init varialbles
    bg=new Image();
    bg.src="garden.jpg";

    bgOffset=0;
    bgVelocity=10;
};

function update(){

}

function draw(){
    ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
    bgOffset+=bgVelocity;
    if(bgOffset>ctx.canvas.width){
        bgOffset=0;
    }
    
    ctx.drawImage(bg,bgOffset,0,ctx.canvas.width-bgOffset,canvas.height,0,0,ctx.canvas.width-bgOffset,canvas.height);
    ctx.drawImage(bg,0,0,bgOffset,canvas.height,ctx.canvas.width-bgOffset,0,bgOffset,canvas.height);
}

function animate(){
    if(!paused){

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

2019年3月4日11点02分

转载于:https://www.cnblogs.com/xiandedanteng/p/10469504.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值