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

Fill an object with an image, not with color (paint image to a canvas)

本文关键字:图像 绘制 对象 颜色 填充      更新时间:2023-09-26

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

您可以使用context.drawImage来绘制播放器图像,而不是矩形

请注意,加载图像需要时间,因此您必须在playerImage.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);
    }
}