Html5画布问题,图像尺寸错误

Luc*_*eos 2 jquery-plugins html5-canvas

我正在尝试创建一个10x10图像的网格.这些是从javascript(对象)加载并使用onload方法将其添加到画布.添加工作,但画布图像似乎调整大小.currentSizes.cellSize的结果是80.然而,即使drawImage参数的宽度和高度值为80,所以添加的图像似乎大于80定义的图像.

我的目标是将画布游戏构建为jQuery插件.我想显示一个带有岛屿的javascript动态创建的网格(就像网络浏览器征服类型的游戏一样).所以我想创建一个100%宽度(和高度)的画布,其中javascript动态测量每个单元格(10x10)的大小.

所以我有以下内容:

                for( var i = 0 ; i < totalTiles ; i++ ) {

                // go to first column in next row
                if( x >= 10 ) {
                    x   = x - 10;
                    y   = y + 1;
                }


                // build the world
                tiles[i]    = new Image();
                tiles[i].x  = x;
                tiles[i].y  = y;
                tiles[i].towidth    = currentSizes.cellSize;
                tiles[i].toheight   = currentSizes.cellSize;
                tiles[i].coordx = ( x * currentSizes.cellSize );
                tiles[i].coordy = ( y * currentSizes.cellSize );
                //tiles[i].onload   = function() { canvas2d.drawImage( tiles[i] , 0 , 0 ); }
                //tiles[i].onLoad   = dibaMethods.drawTile( tiles[i] , ( x * currentSizes.cellSize ) , ( y * currentSizes.cellSize ) , canvas2d );
                tiles[i].src    = "/images/world/tiles/card5.png";

                lastIndex   = i;

                console.log( "looping at: " + i + " with x/y: " + x + "/" + y + " and coordinates: " + tiles[i].coordx + "/" + tiles[i].coordy );

                x++;
            }
            console.log( "Canvas tiles entered, loaded on DOM load, tiles added: " + tiles.length );
            tiles[lastIndex].onload     = function() {
                for( var i = 0; i < totalTiles ; i++ ) {
                    canvas2d.drawImage( tiles[i] , tiles[i].coordx , tiles[i].coordy );
                    //canvas2d.drawImage( tiles[i] , tiles[i].coordx , tiles[i].coordy , tiles[i].towidth , tiles[i].toheight );
                }
            }
Run Code Online (Sandbox Code Playgroud)

画布的HTML:

<canvas id="world">
</canvas>
Run Code Online (Sandbox Code Playgroud)

样式表:

    body { margin: 0; }
    canvas#world { clear: both; background: url("/images/world/clouds.jpg") no-repeat; width: 800px; height: 800px; }
Run Code Online (Sandbox Code Playgroud)

你可以看到我在网址上走了多远:https://battles.hyn.me/world

任何建议都非常感谢!如果问题需要详细说明,请评论!

Luc*_*eos 5

该问题源自没有width或height属性的canvas元素.

在编辑html以包含这些属性并删除样式表条目后,它最终起作用.

所以底线,总是向canvas元素添加width和height属性.