Javascript,显示透明图像。

时间:2014-04-04 10:45:59

标签: javascript canvas html5-canvas

<!DOCTYPE html>
<html>
<head>
<style>
    #container { 
    width: 320px; 
    height: 480px;
    border: 1px solid red;

    }
</style>

</head>
<body>


<div style="position: relative;" id="container">
 <canvas id="myCanvas" width="320" height="480" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
    <canvas id="plane" width="320" height="480" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>

 <canvas id="canvas2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
<img id="scream" src="http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png" alt="The Scream" width="0" height="0">



<script>
var c=document.getElementById("myCanvas");
var c2=document.getElementById("canvas2");
var c3=document.getElementById("plane");

var plane;
var ground;
var score1 = "1"
var score = score1;
var increase = 6;
var delay = 40;
var scorez;

start();

function start(){
    backgrounds();
    planeDraw();
    var scorez = setInterval(scoring, delay);

}


function backgrounds(){
    var ctx=c.getContext("2d");
    var my_gradient=ctx.createLinearGradient(0,0,0, 280);
    my_gradient.addColorStop(0,"white");
    my_gradient.addColorStop(1,"blue");
    ctx.fillStyle=my_gradient;
    ctx.fillRect(0,0,320,480);

    ground = c.getContext("2d");
    ctx.fillStyle="black";
    ctx.fillRect(0,450 , 320 ,30);

}

function scoring(){
    scores();
    score2();

}
function scores(){
    score -= 3-(3+increase);
}
function score2(){
    //var canvas = document.getElementById('canvas2');
    var context = c2.getContext('2d');
    context.clearRect(0, 0, c2.width, c2.height);
    var w = c2.width;
    c2.width = 1;
    c2.width = w;

    var text=c2.getContext("2d");
    text.font="20px Georgia";
    text.fillText(score ,15,20);

}


function hit(){

}

function loes(){
    clearInterval(scorez);

}

function planeDraw(){
    plane = c3.getContext('2d');
    var img = new Image();
    img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png

    plane.drawImage(img, 0, 0, 320, 100);

}
</script> 
<!--
http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png

--!>
</body>
</html>

所有代码似乎都运行正常,我发现的唯一问题是飞机的图像不打印。有人可以告诉我我做错了什么。谢谢。 当我更改planeDraw函数以创建一个矩形时,它完美地工作。除此之外,代码在JSFiddle中工作,当它被隔离时。

2 个答案:

答案 0 :(得分:1)

您正在加载之前绘制图像。

加载平面图像一次,并在其onload事件触发后绘制。

如果可以,请考虑将图片嵌入data:网址,因为这样就无需等待图片加载,但请记住,这会让您的代码更大!

答案 1 :(得分:1)

在绘制图像之前,您必须等待图像加载。 尝试:

img.onload = function()
{
    plane.drawImage(img, 0, 0, 320, 100);
};
img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png

在设置src属性之前定义onload函数是最好的 - 取决于浏览器,如果图像文件在缓存中,onrc事件可能会在src设置后立即触发(在你拥有之前)有机会定义onload)。