问答详情
源自:2-1 绘制背景

背景图片出不来怎么办?

html:

<!DOCTYPE HTML>
<html>
<head>
<meate charset="utf-6">
<title>tinyHeart</title>
<style type="text/css">
body{
   padding-top:10px;
}
.all_bg{
    width:800px;
    height:600px;
    margin:0 auto;
}
#allcanvas{
    position:reative;
    width:800px;
    height:600px;
    margin:0px;
}
#canvas1{
    position:absolute;
    bottom:0;
    left:0;
    zindex:1;
}
#canvas2{
    position:absolute;
    bottom:0;
    left:0;
    zindex:0;
}
</style>
</head>
<body>
<div class="all_bg">
<div id="allcanvas">
<canvas id="canvas1" width="800" height="600"></canvas>
<canvas id="canvas2" width="800" height="600"></canvas>
</div>
</div>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/commonFunctions.js"></script>
<script type="text/javascript" src="js/background.js"></script>
<script type="text/javascript" src="js/ane.js"></script>
<script type="text/javascript" src="js/fruit.js"></script>
</body>
<html>

main.js:

var can1;
var can2;
var ctx1;
var ctx2;
var canWidth;
var canHeight;
var lastTime;
var deltaTime;
var bgPic= new Image();
document.body.onload=game;
function game(){
    init();
    lastTime=Date.now();
    deltaTime=0;
    gameloop();
   
}
function init(){
   //获得canvas  context
  can1 = document.getElementById("canvas1");

ctx1 = can1.getContext('2d');   //fishes dust UI circle

can2 = document.getElementById("canvas2");

ctx2 = can2.getContext('2d');   //background ane fruits
    bgPic.src="./src/background.jpg";
    canWidth=can1.width;
    canHeight=can1.height;
    ane = new aneObj();
    ane.init();
    fruit=new fruitObj();
    fruit.init();
}
function gameloop(){
   window.requestAnimFrame(gameloop);
          var now=Date.now();
     deltaTime= now - lastTime;
     lastTime=now;
     drawBackground();
     ane.draw();
     fruit.draw();
     
}

background.js:

function drawBackground(){
     ctx2.drawImage(bgPic,0,0,canWidth,canHeight);
}

提问者:qq_慕桂英518206 2019-03-22 14:01

个回答

  • 慕雪8111538
    2021-04-15 11:03:30

    把最后的background.js改为这样就可以显示图片了。

    bgPic.onload = function() {

        ctx2.drawImage(bgPic, 0, 0, canWidth, canHeight);

    }


  • shaochunliang
    2019-04-21 22:58:52

    <!DOCTYPE HTML> 改为 <!DOCTYPE THML>

  • 慕粉2108515006
    2019-04-09 21:20:32

    刷新一下试试