How do i load spritesheet in the middle of my canvas?

28 Views Asked by At

Im trying to position my spritesheet somewhere in the middle of my screen, but when i scale my browser the spritesheet slips to a different position…

ctx.drawImage(playerImage, frameX, frameY, spriteWidth, spriteHeigh, 270, 100, spriteWidth, spriteHeigh);

Here i moved it a bit around with 270, 100 coordinates but it fit only at certain scale and when i change it it moves….

Here is my entire code from js

let playerState = 'one';
const dropdown = document.getElementById('animations');
dropdown.addEventListener('change', function(e){
    playerState = e.target.value;
})

const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');

const CANVAS_WIDTH = canvas.width = 1100;
const CANVAS_HEIGHT = canvas.height = 500;

//canvas.width = 1100;
//canvas.height = 500;

const playerImage = new Image();
playerImage.src = 'sprite_sheet.png';

const spriteWidth = 366;
const spriteHeigh = 300;


//let frameX = 0;
//let frameY = 0;
let gameFrame = 0;
const staggerFrame = 5;
const spriteAnimations = [];
const animationStates = [
    
    {
        name:'idle', 
        frames: 7,
    },
    {
        name:'one', 
        frames: 7,
    },
    {
        name:'two', 
        frames: 7,
    },
    {
        name:'tree', 
        frames: 9,
    },
    {
        name:'four', 
        frames: 11,
    },
    {
        name:'five', 
        frames: 5,
    },
    {
        name:'six', 
        frames: 7,
    },
    {
        name:'seven', 
        frames: 7,
    },
    {
        name:'eight', 
        frames: 12,
    },
    {
        name:'nine', 
        frames: 4,
    },
];

animationStates.forEach((state, index) => {
 let frames = {
     loc: [],
 }   
 for (let j = 0; j < state.frames; j++){
     let positionX = j * spriteWidth;
     let positionY = index * spriteHeigh;
     frames.loc.push({x: positionX, y: positionY});
     
 }
    spriteAnimations[state.name] = frames;
});

console.log(animationStates);

function animate (){
    
    ctx.clearRect(0,0, canvas.width, canvas.height);
    //ctx.fillRect(100,50,100,100);
    
    //ctx.drawImage(playerImage, 200, -40);
    //ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
    let position = Math.floor(gameFrame/staggerFrame) % spriteAnimations[playerState].loc.length;
   let frameX = spriteWidth * position;
    let frameY = spriteAnimations[playerState].loc[position].y;
    
    
    ctx.drawImage(playerImage, frameX, frameY, spriteWidth, spriteHeigh, 270, 100, spriteWidth, spriteHeigh);
    
    
    gameFrame++;
    requestAnimationFrame(animate);
};

animate();

0

There are 0 best solutions below