书籍名称:HTML5-Animation-with-JavaScript
书籍源码:https://github.com/lamberta/html5-animation
1.canvas的context
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
第一句是获取canvas节点。
第二句是获取一个 CanvasRenderingContext2D 对象,绘画功能如clearRect,lineTo等都是这个对象的属性.(getContext目前只支持2d)。
2.清除绘画
context.clearRect(x, y, width, height) 前两个属性是开始的坐标,后两个是结束的坐标,目标函数的作用就是清空这两个点构成的正方形。如先前使用,实际就是清空整个画板。
context.clearRect(0, 0, canvas.width, canvas.height);
3.画笔样式
strokeStyle:用来设置颜色,可以是CSS颜色值属性,可以是渐变,可以是图案,默认#000000。
lineWidth:画笔大小,默认为1.
lineCap:线冒,线两端的样子,三个属性butt,round,square.默认是butt。(http://www.w3school.com.cn/tiy/t.asp?f=html5_canvas_linecap)
lineJoin: 线交汇处,两条线交汇的样子,三个属性round,bevel,miter,默认miter(http://www.w3school.com.cn/tiy/t.asp?f=html5_canvas_linejoin)
miterLimit:lineJoin设置为miter时,控制这个miter的长度限制,当超出这个长度显示为bevel(http://www.w3school.com.cn/tiy/t.asp?f=html5_canvas_miterlimit)
4.lineTo和moveTo
完整的画一条线的代码是这样的,第一句beginPath(),开始路径绘画,第二句,moveTo将坐标移动到七点;第三句生成一条直接到坐标100,100,第四局,stroke对先前生成的内容在canvas上显示。
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'); context.beginPath();
context.moveTo(0, 0);
context.lineTo(100, 100);
context.stroke();
创建一个绘画程序
01-drawing-app.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Drawing App</title>
<link rel="stylesheet" href="../include/style.css">
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="400" height="400"></canvas>
<aside>Click and draw with the mouse.</aside> <script src="../include/utils.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas); canvas.addEventListener('mousedown', function () {
context.beginPath();
context.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onMouseMove, false);
}, false); canvas.addEventListener('mouseup', function () {
canvas.removeEventListener('mousemove', onMouseMove, false);
}, false); function onMouseMove () {
context.lineTo(mouse.x, mouse.y);
context.stroke();
}
};
</script>
</body>
</html>
5.