使用图像填充对象,而不是使用颜色(将图像绘制到画布)

时间:2016-05-14 16:24:19

标签: javascript html object canvas

我正在创建一个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();
}

1 个答案:

答案 0 :(得分: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);
    }
}