2016-05-14 96 views
0

我创建了一个Javascript游戏,并且想知道是否有人可以帮助我处理这些对象。而不是用颜色来填充物体,我想要一个填充物体的图像。如何才能做到这一点?用图像填充对象,不用颜色(将图像绘制到画布上)

JSFIDDLE

var PlayerX; 

var canvas = document.getElementById("gamefield"); 
ctx = canvas.getContext("2d"); 

PlayerX = new Player(); 

function Player() 
{ 
    this.width = 30; 
    this.height = 50; 
    this.x = canvas.width/4; 
    this.y = canvas.height/3*2; 
    this.draw = function(){ 
     ctx.fillStyle="#00BFFF"; 
     ctx.fillRect(this.x, this.y, this.width, this.height); 
    } 
} 

function Update() 
{ 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    PlayerX.draw(); 
} 
+0

当你说“填充”对象时,你是什么意思?包括图像很容易,但如果您想开始将其融入形​​状,则会变得更加复杂。 – DBS

+0

@DBS我想要获得一个图像作为播放器。在我的JSFIDDLE示例中,我的播放器是蓝色的。我试图取得一个PNG文件,而不是蓝色。 – Nielsvangils

+0

@Nielsvangils你有什么理由为什么要使用画布?而不是简单的DOM元素?也关于你的问题,你不会用图像填充矩形,你只需创建另一个项目,这是一个图像在矩形的相同大小/位置 –

回答

3

您可以使用context.drawImage提请您playerImage,而不是一个矩形。

请注意,图片加载需要一段时间,因此您必须在playerImage.onload回调内创建播放器。你还必须在这个onload中启动你的游戏循环。

var PlayerX; 

var canvas = document.getElementById("gamefield"); 
ctx = canvas.getContext("2d"); 

var playerImg=new Image(); 
playerImg.onload=start; 
playerImg.src="putYourImageHere.png"; 
function start(){ 
    PlayerX = new Player(); 
} 

function Player() 
{ 
    this.width = 30; 
    this.height = 50; 
    this.x = canvas.width/4; 
    this.y = canvas.height/3*2; 
    this.draw = function(){ 
     ctx.drawImage(PlayerImg,this.x, this.y); 
    } 
}