JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas"></canvas>
CSS
* {
margin: 0;
padding: 0;
}
JavaScript
//L'objet Personnage
function Personnage (url) {
this.url = url;
this.image = new Image();
this.charge = false;
this.x = 0;
this.y = 0;
// Pourquoi ne pas charger dès la création de l'objet ?
this.charger(this.url);
};
Personnage.prototype.charger = function(fichier) {
var self = this;
this.charge = false;
this.image.src = fichier;
this.image.addEventListener("load", function() {
self.charge = true; // <-- Si tu utilise "this" ici, tu vas accèder à l'évenement, pas à ton personnage!
console.log("L'objet a été chargé:", this); // Préfère les console.log aux alerts, parce que c'est plus polyvalent et moins contraignant pour débugger... Tu peux accèder aux messages de la console dans l'inspecteur web.
}, false);
};
Personnage.prototype.afficher = function(context) {
if (this.charge) { //si l'image est chargée
context.drawImage(this.image, this.x, this.y)
}
};
Personnage.prototype.deplacer = function(dx, dy) {
this.x += dx;
this.y += dy;
};
var Game = function() {
this.setup(); // Lance la fonction "setup"
};
Game.prototype = {
setup: function() {
var self = this; // Pour pouvoir accèder à l'objet dans l'EventListener
this.canvas = document.getElementById("canvas");
this.canvas.height = window.innerHeight;
this.canvas.width = window.innerWidth;
this.context = this.canvas.getContext("2d");
window.addEventListener("keydown", function() { // préférable à "onkeydown = ..."
if (event.which == 39 || event.keyCode == 39) {
self.zozor.deplacer(5, 0);
}
}, false);
this.draw();
},
creerZozor: function() {
this.zozor = new Personnage("http://fr.openclassrooms.com/uploads/fr/ftp/iphone/zozor.png");
},
draw: function() { // Fonction pour afficher tous les élements du canvas, est appelé en boucle
// On clear...