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

本文探讨了HTML5 Canvas中坐标系统与实际显示尺寸之间的差异导致的鼠标位置偏差问题,并给出了具体的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      今天写了个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>

 

转载于:https://www.cnblogs.com/lgmcolin/archive/2013/05/11/3072830.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值