HTML5-Canvas
说明:本文及文章最后所附相关文章,是我对于书籍《Pro HTML5 Programming》英文版的个人学习总结。
一.Using the HTML5 Canvas API
1.convas坐标系统
Convas中的坐标系统以convas的左上角为坐标原点,水平坐标从左到右递增,垂直坐标从上到下递增。
2.CSS and Canvas
大多数CSS样式可应用于convas。
3.让IE9以下版本中支持convas
可以在http://code.google.com/p/explorercanvas下载一个JS库让IE9以下版本支持convas。使用该库的方法如下:
<head>
<!--[if IE]><script src="excanvas.js"></script><![endif]-->
</head>
4.检查浏览器对convas的支持性
<canvas>
Update your browser to enjoy canvas!
</canvas>
try
{
document.createElement("canvas").getContext("2d");
document.getElementById("support").innerHTML =
"HTML5 Canvas is supported in your browser.";
}
catch (e)
{
document.getElementById("support").innerHTML = "HTML5 Canvas is not supported in your browser.";
}
5.定义一个convas并设置属性和样式
<canvas id="diagonal" style="border: 1px solid;" width="200" height="200">
</canvas>
6.获取convas和其绘图上下文
var canvas = document.getElementById('diagonal');
var context = canvas.getContext('2d');
7.通常在坐标原点绘制某个对象,以后可对该对象应用坐标变换、缩放、翻转等操作,这样便于代码重用。
8.通常在一段新绘制或修改操作前应该调用context.save()方法保存convas的原始状态(没有进行任何绘制或更改),每次在一段新绘制或修改操作结束后再调context.restore()方法将其恢复到原始状态。这样有利于以后的绘制操作。
9.在convas中使用图像
HTML5 Canvas API具有在convas中操作图像的功能,但要使图像能够在convas中呈现,图像必须完全已加载完毕。但浏览器通常异步加载图像,因此必须用相应的技术处理等待图像加载完毕。如:
// Load the bark image
var bark = new Image();
bark.src = "bark.jpg";
// Once the image is loaded, draw on the canvas
bark.onload = function () {
drawTrails();
}
10.If you perform a rotate transform to a shape drawn off origin, a rotate transform will rotate the shape around the origin rather than rotating in place. Similarly, if you performed a scale operation to shapes before translating them to their proper position, all locations for path coordinates would also be multiplied by the scaling factor. Depending on the scale factor applied, this new location could even be off the canvas altogether, leaving you wondering why your scale operation just ‘deleted’ the image.”
11.canvas的状态
canvas的状态实际上是指其绘图环境context的状态,而不是绘制内容的状态,因此,状态的改变不会影响之前已绘制好的可见内容。当改变context的属性,或者进行旋转、缩放、翻转等操作都会改变context的状态。因此要灵活地运用save()、restore()、translate()等方法。
相关文章:
HTML5-Cross Document Messaging APIs