【问题标题】:Canvas can't draw a square?画布不能画正方形?
【发布时间】:2011-10-09 03:04:59
【问题描述】:
    <canvas id="c" style="border: solid 1px black; width: 300px; height: 300px;"></canvas> 
    <script type="text/javascript">
        var canvas = document.getElementById("c"),
        ctx = canvas.getContext("2d");
        ctx.fillRect(0, 0, 50, 50);
    </script>  

结果:

小提琴:http://jsfiddle.net/wong2/xZGUj/

【问题讨论】:

标签: javascript html canvas


【解决方案1】:

问题是画布的样式属性。

使用 style 属性设置画布的大小会导致缩放问题。 发生这种情况是因为画布元素具有默认大小。如果您使用 css 设置大小,则它不同于该大小 => 缩放问题。你可以 alert(canvas.height) 并且你会看到它有一个值,即使你没有设置一个。

如果您更改为以下内容,它将起作用:

<canvas id="c" width="100" height="100" style="border: solid 1px black;"></canvas> 
<script type="text/javascript">
    var canvas = document.getElementById("c"),
    ctx = canvas.getContext("2d");
    ctx.fillRect(0, 0, 50, 50);
</script>  

【讨论】:

  • Setting the size of the canvas using the style attribute will result in scaling issues 为什么?
  • 我用解释改变了我的答案。
【解决方案2】:

你可以把宽度和高度作为画布的属性 看看这个http://jsfiddle.net/Fedor/xZGUj/3/

我猜,属性宽度和高度初始化坐标系统洞察画布。 css 属性仅限制画布的大小。因此,当您不指定宽度和高度时,默认情况下您将获得宽度=300 和高度=150 的坐标系。你可以在这里找到这些信息http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width

所以如果你在你的小提琴中把高度放在 css 150...squre 将是 squre :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2016-08-05
    • 2018-03-20
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多