Adding sprite to a player class in vanilla JavaScript


I made a player class for my game, but I’m not sure how to insert my player sprite into it. I am using vanilla JavaScript for this.

My Player Class:

    constructor(x, y, color, width, height, health, strength, type, speed, jumpspeed) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.width = width;
        this.height = height;
        this.health = health;
        this.strength = strength;
        this.type = type;
        this.speed = speed;
        this.jumpspeed = jumpspeed;
    }
    draw() {
        c.beginPath();
        c.rect(this.x, this.y, this.width, this.height);
        c.fillStyle = this.color;
        c.fill();
        c.stroke();
    }
}

Here is where I call it:

const playerSprite = new Image();
playerSprite.src = "Images/CatIW1.png";
const background = new Image();
background.src = "Images/world1bg.png";

function animate(){
    c.drawImage(background, 0 ,0, canvas.width, canvas.height);
    requestAnimationFrame(animate);    
}
animate();

var player = new Player(x, y, 'red', 64, 32, 100, 30, 'basic', speed, jumpspeed);
player.draw();

Source: CSS – Stack Overflow

November 21, 2021
Category : News
Tags: Canvas | css | game-development | html | javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.