【问题标题】:drawing an image inside a canvas在画布内绘制图像
【发布时间】:2019-09-12 13:34:27
【问题描述】:

代码:

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();

图片:

画布:&lt;canvas id="MyCanvas" width="400" height="400"&gt;&lt;/canvas&gt;

我要做的基本上是沿着画布宽度cw 的第一行绘制第一个灰色瓷砖。注意我不能使用平铺数组来绘制它,这个函数不是绘图任何事情,我不知道为什么有人可以帮助我
jsfiddle:http://jsfiddle.net/seekpunk/B2nUs/36/

【问题讨论】:

  • 在循环中使用 i += 28 而不是 i + 28
  • 我看不到cw 的定义位置,它是循环的退出条件。这似乎很重要。您也没有在循环中增加 i - i+=28 怎么样(或更长的形式,i=i+28
  • 我更新了我的代码请检查小提琴它没有画任何东西
  • 大声笑是的!!!请告诉我为什么这个功能不起作用?

标签: javascript html canvas


【解决方案1】:

我修改了你的代码,这是我的 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();
}

【讨论】:

  • 但这不是我的目标,我只需要在画布的第一行绘制灰色瓷砖
  • 好的,我已将其更改为仅绘制第一行! jsfiddle.net/yalight/FT8M2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2013-04-25
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多