*课程最终成果展示:
CodePen: https://codepen.io/YitingLi/full/jwjgdP/
GitHub: https://github.com/Liyiting/canvas-Gorgeous-clock-effects*
HTML
html5的一个新的标签。
<canvas id="canvas"></canvas>
不指定长宽时,默认是300px*150px
<canvas id="canvas" width="1024" height="768"></canvas>
这里的宽高没有单位,因为他们也决定了canvas画布内里的精度
Javascript
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d')
//使用context进行绘制
Canvas
- canvas.width
- canvas.height
- canvas.getContext(‘2d’)
Draw a line 绘制直线
Canvas是基于状态的绘制
context.moveTo(100, 100)//下笔处
context.lineTo(700, 700)//画到哪儿
context.lineWidth = 5 //线条宽度
//空心
context.strokeStyle = "#005588" //线条颜色
context.stroke() //画!
//实心
context.fillStyle = "rgb(2,100,30)"//填充颜色
context.fill()
//路径分开绘制
//closePath的意思不是结束路径,而是闭合当前路径使得所有线段连接。它会试图从当前路径的终点连一条路径到起点,让整个路径闭合起来。(这样才能填色吗不是)但是,这并不意味着它之后的路径就是新路径了,要开启新路径,仍然需要使用beginPath,简单说,closePath和beginPath其实没有任何联系的。
context.beginPath()
context.closePath()
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title></title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid #aaa;display: block; margin: 0 auto;">
当前浏览器不支持Canvas, 请更换浏览器后再试。
</canvas>
<script>
var tangram = [
{p:[{x:0, y:0},{x:800, y:0},{x:400, y:400}], color: "#caff67"},
{p:[{x:0, y:0},{x:400, y:400},{x:0, y:800}], color: "#67becf"},
{p:[{x:800, y:0},{x:800, y:400},{x:600, y:600},{x:600, y:200}], color: "#ef3d61"},
{p:[{x:600, y:200},{x:600, y:600},{x:400, y:400}], color: "#f9f51a"},
{p:[{x:400, y:400},{x:600, y:600},{x:400, y:800},{x:200, y:600}], color: "#a594c0"},
{p:[{x:200, y:600},{x:400, y:800},{x:0, y:800}], color: "#fa8ecc"},
{p:[{x:800, y:400},{x:800, y:800},{x:400, y:800}], color: "#f6ca29"}
]
window.onload = function() {
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 800;
var context = canvas.getContext("2d")
for(var i = 0; i < tangram.length; i++){
draw(tangram[i], context);
}
}
function draw(piece, cxt){
cxt.beginPath();
cxt.moveTo(piece.p[0].x, piece.p[0].y);
for(var i = 1; i<piece.p.length; i++) {
cxt.lineTo(piece.p[i].x, piece.p[i].y);
}
cxt.closePath();
cxt.fillStyle = piece.color;
cxt.fill();
cxt.strokeStyle = "black";
cxt.lineWidth = 3;
cxt.stroke();
}
</script>
</body>
</html>
Draw an arc 绘制弧线
context.arc(
centerx, centery, radius, //圆心坐标及半径
startingAngle, endingAngle, //起始弧度制
anticlockwise = false //顺/逆时针
//对于一个圆来说0pi在右边,顺逆时针角度不变
)
closePath对于fill来说是没有用的,因为调用fill时canvas会自动把没有closePath的路径首尾相连
clearRct(x,y,width, height)//对矩形区域进行一次刷新操作