canvas width/height和style.width/style.height

      今天写了个canvas的热点图测试,发觉画笔的点和鼠标的位置不一致,有挺大的偏差。开始还以为是jq中位置函数引用错误,offset和pageX...那几个的属性再看了遍,发觉没什么问题。后来google了下,发觉是html5的canvas问题,这是一个很常见的误区!!

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 integersThe 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.

其实这里已经说的很明白,通俗点说就是在canvas中定义width、height跟在style中定义width和height是不同的,canvas标签的width和height是画布实际宽度和高度,绘制的图形都是在这个上面。而style的width和height是canvas在浏览器中被渲染的高度和宽度。如果canvas的width和height没指定或值不正确,就被设置成默认值(width:300px,height:150px) 

于是明白了...代码中是这么写的..看我是没有设置width和height属性,然后发觉鼠标的偏差好像就是style中的widht和height... 

<div id="canvasPanel">
<canvas id="canvas" width="500" height="300" style="border:1px solid;width:200px;height:200px;" ></canvas>
<input type="button" id="clear" value="clear" />
</div>

 

posted @ 2013-05-11 15:42  GM_Lv  阅读(349)  评论(0编辑  收藏  举报