2014-02-11 95 views
2

代碼:繪製畫布內部的圖像

function DrawLevel1() { 
    Pos = 1; 
    w = 84; 
    h = 84; 
    x = 28; 
    y = 28; 
    for (i = 0; i < cw; i += 28) { /// use += 

     ctx.drawImage(tankImg, 
        (Pos - 1) * w, /// x of source (use 0-based indexes) 
        0,   /// y of source 
        w,   /// width of source 
        h,   /// height of source 
        i,   /// x in destination (visible canvas) 
        y,   /// y, width and height of the resulting 
        w, h);  /// image 
     x += 28; 
     y += 28; 
    } 
} 

DrawLevel1();

圖像:

http://oi62.tinypic.com/148yf7.jpg http://oi62.tinypic.com/148yf7.jpg

帆布:<canvas id="MyCanvas" width="400" height="400"></canvas>

什麼,我試圖做的基本上是借鑑第一灰瓦一直畫布cw .notice的寬度的第一行我不能使用平鋪陣列並繪製它,這個函數並沒有畫任何東西,我想不出爲什麼有人能幫我請
jsfiddle:http://jsfiddle.net/seekpunk/B2nUs/36/

+0

使用'我+ = 28'而不是'i + 28'在你的循環中。 – Sebastian

+0

我沒有看到'cw'是在哪裏定義的,它是你的循環的退出條件。這似乎很重要。你還沒有在你的循環中遞增'i' - 那麼'i + = 28'(或更長的形式,'i = i + 28')怎麼樣? – Krease

+0

我更新了我的代碼,請檢查小提琴它沒有繪製任何東西 – Sora

回答

2

我修改代碼,這是我的jsfiddle http://jsfiddle.net/yalight/5cHQF/

function DrawLevel1() { 
    Pos = 1; 
    w = 84; 
    h = 84; 
    x = 28; 
    y = 28; 
    for (i = 0; i < cw; i += 28) { /// use += 
     for(j = 0; j< cw; j += 28) { 

      ctx.drawImage(tankImg, 
        0, /// x of source (use 0-based indexes) 
        0,   /// y of source 
        w,   /// width of source 
        h,   /// height of source 
        i,   /// x in destination (visible canvas) 
        j,   /// y, width and height of the resulting 
        w, h);  /// image 
      x += 28; 
      y += 28; 
     } 
    } 
} 

只畫第一行http://jsfiddle.net/yalight/FT8M2/

function DrawLevel1() { 
    w = 84; 
    h = 84; 
    x = 28; 
    //y = 28; 
    for (i = 0; i < cw; i += x) { /// use += 
     ctx.drawImage(tankImg, 
      0,  /// x of source (use 0-based indexes) 
      0,  /// y of source 
      w,  /// width of source 
      h,  /// height of source 
      i,  /// x in destination (visible canvas) 
      0,  /// y, width and height of the resulting 
      w, h); /// image 
    } 
} 

而且你應該叫DrawLevel1在這裏:

function Draw() { 
    ctx.clearRect(0, 0, cw, ch); 
    DrawLevel1(); // here 
    PlayerTank.draw(); 
    Missiles.draw(); 
    Enemies.draw(); 
} 
+0

但這不是我想要的目標,我只需要在畫布的第一行繪製灰色瓷磚 – Sora

+0

好吧,我已將其更改爲僅繪製第一行! http://jsfiddle.net/yalight/FT8M2/ – yalight

+0

非常感謝 – Sora