1.1
标签设置width与height属性同时设置了绘制大小与元素大小;
实用css约束canvas标签,则约束了元素大小,若绘图大小与元素大小不一致,则会发生拉伸或者缩放,使得绘图大小满足元素大小。
举个例子,css属性设置宽600高300,而绘制大小不指定(默认宽300高150)那么最后图像会被拉伸两倍
canvas属性仅两个width与height,方法有getContext、toDataUrl以及toBlob。getContext用于获取绘图环境。toDataUrl(type,quality)返回一个数据地址(简单理解就是返回一个图片地址给你,能用于img标签展示);toBlob(callback,type,args...)创建一个blob。这三个方法目前只见过第一个的使用,后面两个不是很熟,不知道理解对不对。以后遇到再说。
1.2 Canvas的绘图环境
canvas可用于2d与3d绘图,3d绘图可能就是webgl。通过canvas.getContext("2d")还是canvas.getContext("3d")来获取绘图上下文。canvas绘图环境包含属性过多,第二章再说。
canvas2d上下文(context)有两个方法save()与restore()非常有用。
1.3 书中规范
没啥好说的,就是通过getElementById获取canvas对象,在使用context = canvas.getContext("2d")获取绘制上下文,然后通过这个context进行一些列操作,比如画个图啥的。
1.4 html5一些基础
没啥说的,略了
1.5基本的绘制操作
这节居然画了个时钟,虽然很基础,但这么第一章就用这些,有点接受不了。主要是canvas绘图API,包括arc、beginPath、clearRect、fill、fillText、lineTo、moveTo以及stroke。
下代码可以去https://github.com/corehtml5canvas/code这里找到。
大体思路就是分别画圆圈、中心、指针以及数字。这个很像本科的一道期末考试题……
1.6事件处理
注册监听事件,这个就是js的内容,比如canvas.onmousedown = function(e){...};或者cavas.addEventListener('mousedown',function(3){...})
注意点:将鼠标坐标转换为canvas坐标
通过canvas.getBountdingClientRect()获取canvas元素边界框,来获得坐标转换。
var bbox = canvas.getBoundingClientRect()
canvas中鼠标坐标为 (e.clientX - bbox.left)*(canvas.width/bbox.width)
注意点:canvas是不可获取焦点的元素。而键盘事件是发生在当前拥有焦点的html元素上。因此,需要在window或document对象上处理键盘监听事件。keydown、keypress与keyup三个事件。
1.7绘制表面的保存与恢复
主要用到了context.getImageData() 以及context.putImageData() 会在第四章做进一步介绍
1.8 canvas中使用html元素
无法将html元素嵌入到canvas中,只能通过css将html元素放在canvas之上。(可以复习一下z-index属性、绝对定位以及相对定位)
1.9打印canvas中内容
toDataUrl获取canvas图像url,将该值传递给img.src属性,进行展示。
toBlob()方法可以保存至一个blob文件
1.10离屏canvas
有点震惊,离屏canvas居然就是display:none,说了我也不信。
1.11基础数学知识
略