4

所有画布标签尺寸都以像素为单位吗?

我问是因为我理解他们是。
但是我的数学被打破了,或者我只是没有在这里掌握一些东西。
我大部分时间都在做python,然后又回到了Java Scripting。
如果我只是在做一些愚蠢的事情,请告诉我。
对于我正在编写的游戏,我想要一个块状渐变。
我有以下内容:

HTML

<canvas id="heir"></canvas>

CSS

@media screen {
    body { font-size: 12pt }
    /* Game Rendering Space */
    canvas { 
        width: 640px; 
        height: 480px; 
        border-style: solid; 
        border-width: 1px;
    }
}

JavaScript (Shortened)

function testDraw ( thecontext )
{
    var myblue = 255;
    thecontext.save(); // Save All Settings (Before this Function was called)
    for (var i = 0; i < 480; i = i + 10 ) {
        if (myblue.toString(16).length == 1) 
        {
            thecontext.fillStyle = "#00000" + myblue.toString(16);
        } else {
            thecontext.fillStyle = "#0000" + myblue.toString(16);
        }
        thecontext.fillRect(0, i, 640, 10);
        myblue = myblue - 2;
    };
    thecontext.restore(); // Restore Settings to Save Point (Removing Styles, etc...)
}

function main ()
{
    var targetcontext = document.getElementById(“main”).getContext("2d");
    testDraw(targetcontext);
}

对我来说,这应该产生一系列 640w x 10h 像素条。在 Google Chrome 和 Fire Fox 中,我得到 15 条。对我来说,这意味着( 480 / 15 )是 32 像素高的条。
所以我将代码更改为:

function testDraw ( thecontext )
{
    var myblue = 255;
    thecontext.save(); // Save All Settings (Before this Function was called)
    for (var i = 0; i < 16; i++ ) {
        if (myblue.toString(16).length == 1) 
        {
            thecontext.fillStyle = "#00000" + myblue.toString(16);
        } else {
            thecontext.fillStyle = "#0000" + myblue.toString(16);
        }
        thecontext.fillRect(0, (i * 10), 640, 10);
        myblue = myblue - 10;
    };
    thecontext.restore(); // Restore Settings to Save Point (Removing Styles, etc...)
}

并得到一个真正的 32 像素高度结果进行比较。除了第一个代码片段在画布的不可见部分呈现蓝色阴影之外,它们的测量值为 32 像素。


现在回到原始 Java 代码...
如果我在 Chrome 中检查 canvas 标签,它会报告 640 x 480。
如果我在 Fire Fox 中检查它,它会报告 640 x 480。
但是!Fire Fox 以 300 x 150(即 15 行,每行 10)将原始代码导出为 png。是否通过 CSS 将大小调整为 640 x 480 而不是设置为真正的 640 x 480?

为什么,如何,什么?O_o 我糊涂了……

4

1 回答 1

4

我相信您只需要在 html 中创建画布时设置画布的宽度和高度。这些值控制画布中坐标空间的大小,默认值为 300 x 150。

<canvas id="heir" width="640" height="480"></canvas>

来自http://dev.w3.org/html5/spec/Overview.html#canvas

canvas元素有两个属性来控制坐标空间的大小:width和height。这些属性在指定时必须具有有效的非负整数值。必须使用解析非负整数的规则来获取它们的数值。如果缺少某个属性,或者如果解析其值返回错误,则必须使用默认值。width 属性默认为 300,height 属性默认为 150。

于 2010-04-19T01:00:46.617 回答