2014-02-11 50 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