在画布中绘制图像

时间:2014-02-11 07:59:07

标签: javascript html5 canvas

代码:

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的宽度的第一行绘制第一个灰色瓷砖。注意我不能使用平铺数组并绘制它,这个函数是没有画任何东西,我无法弄清楚为什么有人可以帮助我 jsfiddle:http://jsfiddle.net/seekpunk/B2nUs/36/

1 个答案:

答案 0 :(得分: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();
}