JSFiddle - React, Tailwind, and code Playground
by brigand
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.2.0/fabric.min.js"></script>
<canvas id='c' width='954' height='485'></canvas>
CSS
body,
html {
height: 100%;
width: 100%;
border: 0;
padding: 0;
}
/* #c {
height: 100%;
width: 100%;
}
*/
JavaScript 1.7
function fetchImage(url) {
const image = new Image();
image.src = url;
return new Promise((resolve, reject) => {
image.onload = () => resolve(image)
image.onerror = reject;
})
}
var promise = fetchImage('https://mr-easy.github.io/files/blog/spritesheet/heroSpritesheet.png');
promise.then(img => {
console.log(img)
})
/* waitForImageToLoad(img).then(() => {
console.log(img)
})
*/
/*
class Game {
constructor() {
this.canvas = document.getElementById('c');
this.ctx = this.canvas.getContext('2d');
this.gameObjects = [];
}
addGameObject(gameObject) {
this.gameObjects.push(gameObject);
}
loop() {
for (const obj of this.gameObjects) {
obj.update();
obj.draw(this.ctx);
}
}
}
class GameObject{
constructor(spritesheet, x, y, timePerFrame, numFrames) {
this.spritesheet = fetchImage(spritesheet);
console.log(this.spritesheet);
this.width = this.spritesheet.width;
this.height = this.spritesheet.height;
// console.log(this.width, this.height);
this.x = x;
this.y = y;
this.timePerFrame = timePerFrame;
this.numFrames = numFrames;
this.frameIndex = 0;
this.lastUpdate = Date.now();
}
update() {
const now = Date.now();
if (now - this.lastUpdate > this.timePerFrame) {
this.frameIndex++;
if (this.frameIndex >= this.numFrames) {
this.frameIndex = 0;
}
this.lastUpdate = now;
}
}
draw(ctx) {
ctx.drawImage(this.spritesheet,
this.frameIndex * this.width / this.numFrames,
0,
this.width / this.numFrames,
this.height,
this.x,
this.y,
this.width / this.numFrames,
this.height);
}
}
*/
/* const g = new Game();
const p = new GameObject('https://mr-easy.github.io/files/blog/spritesheet/heroSpritesheet.png', 0, 0, 80,...