画布不能画正方形吗? [英] Canvas can't draw a square?
本文介绍了画布不能画正方形吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<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>
结果为:
Result in :
小提琴: http://jsfiddle.net/wong2/xZGUj/
推荐答案
问题出在画布的样式属性上。
The problem is the style attribute of the canvas.
使用样式属性设置画布的大小会导致缩放问题。
发生这种情况是因为canvas元素具有默认大小。如果使用css设置大小,则不同于该大小=>缩放问题。您可以警报(canvas.height),即使您未设置值,它也会具有一个值。
Setting the size of the canvas using the style attribute will result in scaling issues. This happens cause the canvas element has a default size. If you set the size using css it differs from that size => scaling issues. You can alert(canvas.height) and you will see that it has a value, even if you dont set one.
如果更改为以下内容,它将起作用:
If you change to the following it will work:
<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>
这篇关于画布不能画正方形吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文