在JS

时间:2018-07-02 01:08:36

标签: javascript html5 image html5-canvas loading

我正在制作带有极坐标的战舰游戏。用户选择两点后,应在中间绘制一艘战舰。我的战舰构造函数如下:

function Battleship(size, location, source){
        this.size = size;
        //initializing the image
        this.image = new Image();
        this.image.src = source;
        this.getMiddlePoint = function(){
           //get midpoint of ship
           ...
        }
        this.distanceBetween = function(t1, t2){
           //dist between two points
        }
        this.display = function(){
          var point = [this.radius];
          point.push(this.getMiddlePoint());
          point = polarToReal(point[0], point[1] * Math.PI / 12);
          //now point has canvas coordinates of midpoint
          var width = this.distanceBetween(this.info[0][0], this.info[this.info.length-1][0]);
          var ratio = this.image.width / width;
          ctx.drawImage(this.image, point[0] - width/2, point[1] - this.image.height / ratio / 2, width, this.image.height / ratio);
          //draws the image
        }
      }

每只船的display方法在某个点(在用户选择位置之后)被调用。由于某些原因,这些图像不会在我第一次执行时显示,而是在最后运行此代码时显示:

for(var i = 0; i<playerMap.ships.length; i++){
    playerMap.ships[i].display();
}

所有船只均正确显示(排列不正确,但已显示)。我认为加载图像有问题。我不确定如何解决此问题。我尝试使用image.onload,但从未成功。我也尝试过这样的事情:

var loadImage = function (url, ctx) {
  var img = new Image();
  img.src = url
  img.onload = function () { 
    ctx.drawImage(img, 0, 0);
  }
} 

,但同样的问题不断发生。请帮助我解决此问题。 Here是目前的状态。如果您放置船只,则什么也不会发生,但是在您放置5(或10)艘船只之后,它们突然全部加载。

编辑:

我通过全局定义图像解决了这个问题。这仍然是非常糟糕的做法,因为我希望将其作为战舰对象。这是我的(临时)解决方案:

 var sub = [];
 for(var i = 1; i<5; i++){
     sub[i] = new Image();
     sub[i].src = "/img/ships/battleship_"+i+".png";
 }

0 个答案:

没有答案