码迷,mamicode.com
首页 > 其他好文 > 详细

canvas.width和canvas.style.width的区别

时间:2015-04-07 23:26:06      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

先让我们来看下代码:

<!DOCTYPE HTML>
<html>
<body>

<canvas id="myCanvas" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>


<script type="text/javascript">

var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
c.style.width=‘200px‘
c.style.height=‘200px‘
var grd=cxt.createLinearGradient(0,0,100,100);
grd.addColorStop(0,"#FF0000");
grd.addColorStop(1,"#00FF00");
cxt.fillStyle=grd;
cxt.fillRect(0,0,100,100);

</script>

</body>
</html>

我的本意是在200*200px的画布上画一个100*100的正方形,但是实际的结果为

技术分享  

为何会这样的?

在w3网站上是这样解释的:

  The canvas element has two attributes to control the size of the coordinate space: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

  The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

 

根据上面的描述,我理解为width/height属性在我们没有设置的时候默认为300,150。但是注意这里并没有跟单位,不是单纯的300px,150px。其实width/height是在为画布分列和分行,比如默认是分为300列200行。在没有指定style.width/height时,1列(行)的宽(高)默认为1px。但是在我们显示指定了css渲染的像素的时候,就会发生改变。

让我们回头看刚才的例子:

我们设置了style.width/height为200x200 px

所画的矩形为100x100

那我按照刚才的理论算一下:

宽200px默认分为300列则实际矩形宽为:(200/300)*100 = 66.6px

高200px默认分为150行则世纪举行高为:(200/150)*100 = 133.3px

由此得以印证

canvas.width和canvas.style.width的区别

标签:

原文地址:http://www.cnblogs.com/sharenz/p/4399818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!