很久没碰canvas了,今天因为canvas绘图的为之问题浪费了一些时间。

我们知道canvas的默认宽高是300X150嘛。

实际使用的时候当然是自定义一个高宽啦。

通常我们会习惯性地在js中通过canvasDom.style设置了某个高宽的时候,canvas在页面上也确实伸缩了。

但是用某些api的时候,传入位置参数时,还是按照300X150规格来处理位置的!如果想让位置居中的话,传入canvas.width/2或canvas.height/2就好了。

这是之前没留意过的问题,今天才发现。可怜我试错地在模拟器上反复折腾,确定真相的我眼前一黑。。。

想来是我孤陋寡闻了,今天又认识了一点点。

--------------------------------华丽分割线----------------------------------

然后我刚刚在外网informit.com看到一篇文章,关于canvas的:

    The difference between using CSS and setting canvas element attributes lies in the fact that a canvas actually has two sizes: the size of the element itself and the size of the element’s drawing surface.

    When you set the element’s width and height attributes, you set both the element’s size and the size of the element’s drawing surface; however, when you use CSS to size a canvas element, you set only the element’s size and not the drawing surface.

----​​http://www.informit.com/articles/article.aspx?p=1903884​​、

大体意思是说:canvas这个元素其实有两种“尺寸”。一种是元素本身的大小。一种是其在绘图时画布的尺寸。

当我们只是改变它的css高宽时,元素在页面上的大小确实改变了。但是在绘图时候,它依旧是按照默认的300X150的规格来处理位置参数。

而如果我们通过canvas的html特性去改变它的宽高,则它的画布尺寸和元素大小都会相应改变。

呜呼,认识又多了一点。

然后试了下把canvasDom.style.xxx改成:



cc.setAttribute('width',w+'px');
cc.setAttribute('height',h+'px');


确实可以哦。