这是我的React代码的一部分。它适用于画布。
componentDidMount(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle="#000";
ctx.fillRect(0,0,2800,2800);
ctx.fillStyle="#eee";
ctx.fillRect(150,150,2500,2500);
var board = this.generateBoard(ctx);
var createImage = function(src){
var img = new Image();
img.src = src;
return img;
}
var images = {
"hero-right": createImage("../../images/hero-right.png"),
"hero-left": createImage("../../images/hero-left.png"),
"treasure": createImage("../../images/treasure.png")
};
var imageCount = Object.keys(images).length;
var imagesLoaded = 0;
for(var key in images){
images[key].onload = function(){
imagesLoaded++;
if(imagesLoaded == imageCount){
startGame();
}
};
}
var startGame = function(){
this.setState({
ctx: ctx,
board: board,
hero:{
img: images["hero-right"],
x: 0,
y:0
}
},
()=>{this.placeItems()}
);
}.bind(this)
},
placeItems(){
this.placeHero();
},
问题是 - 我需要调用这段代码:
this.setState({
ctx: ctx,
board: board,
hero:{
img: images["hero-right"],
x: 0,
y:0
}
},
()=>{this.placeItems()}
);
加载完所有图片后我设法做到了。但它很难看。请帮助我做得更好。