首页 > 代码库 > Canvas学习

Canvas学习

参考了慕课网课程:炫丽的倒计时效果Canvas绘图与动画基础 
感谢  liuyubobobo 老师 ,提供了这么好的课程
1、<canvas><canvas>标签
    注意:最好在标签中指定canvas的width 和 height 或者用js : canvas.width , canvas.height
    <canvas>如果你的浏览器支持canvas,那么你将看不到这行文字</canvas>
    注意:canvas是基于状态来绘制的。
2、画一条直线:
  1.      var canvas = document.getElementById("line"); //获取画布节点
  2. canvas.width = 1366; //设置画布的宽
  3. canvas.height = 600; //设置画布的高
  4. if(canvas.getContext){
  5. var ctx = line.getContext("2d");
  6. ctx.moveTo(100,100); //移动到位置(100,100)
  7. ctx.lineTo(500,500); //从位置(100.100)画线到 位置 (500,500)
  8. ctx.lineTo(100,500); //从位置(500,500)画线到 位置 (100,500)
  9.    ctx.lineTo(100,100);
  10. ctx.stroke();
  11. }
效果图:
 
修改之前的代码如下:
 
  1.       var canvas = document.getElementById("line");
  2. canvas.width = 1366;
  3. canvas.height = 600;
  4. if(canvas.getContext){
  5. var ctx = line.getContext("2d");
  6. ctx.beginPath();// 开始一段新的画
  7. ctx.moveTo(100,100);
  8. ctx.lineTo(500,500);
  9. ctx.lineTo(100,500);
  10. ctx.lineTo(100,100);
  11. ctx.fillStyle = "#6699cc"; //设置填充颜色
  12. ctx.fill(); //执行填充操作
  13. ctx.lineWidth = 5; //设置线宽
  14. ctx.strokeStyle = "rgba(0,255,0,.5)"; //设置画线的颜色
  15. ctx.stroke(); //画线(会基于之前设置的三个 lineTo的坐标位置而依次画图)
  16.         ctx.closePath(); //结束这段画
  17. }
效果如下:
 

熟练之后可以用下面这段代码画出一个美丽的七巧板:
  1. var tangram = [
  2. {p:[{x:100,y:100},{x:300,y:300},{x:500,y:100}],color:‘#CAFF67‘},
  3. {p:[{x:100,y:100},{x:300,y:300},{x:100,y:500}],color:‘#6699CC‘},
  4. {p:[{x:100,y:500},{x:200,y:400},{x:300,y:500}],color:"pink"},
  5. {p:[{x:200,y:400},{x:300,y:300},{x:400,y:400},{x:300,y:500}],color:‘purple‘},
  6. {p:[{x:300,y:300},{x:400,y:200},{x:400,y:400}],color:‘yellow‘},
  7. {p:[{x:400,y:200},{x:500,y:100},{x:500,y:300},{x:400,y:400}],color:‘red‘},
  8. {p:[{x:300,y:500},{x:500,y:300},{x:500,y:500}],color:‘orange‘}
  9. ]
  10. window.onload = function(){
  11. var canvas = document.getElementById("line"),
  12. i = 0;
  13. canvas.width = 1366;
  14. canvas.height = 600;
  15. if(canvas.getContext){
  16. var context = canvas.getContext("2d");
  17. for(i = 0;i<tangram.length;i++){
  18. draw(tangram[i],context)
  19. }
  20. }
  21. }
  22. function draw(piece,cxt){
  23. cxt.beginPath();
  24. cxt.moveTo(piece.p[0].x,piece.p[0].y);
  25. var i = 1;
  26. for(;i < piece.p.length;i++){
  27. cxt.lineTo(piece.p[i].x,piece.p[i].y);
  28. }
  29. cxt.closePath();
  30. cxt.fillStyle=piece.color;
  31. cxt.fill();
  32. cxt.fillStyle = "#000000";
  33. cxt.lineWidth = 3;
  34. cxt.stroke();
  35. }
效果图:
 
另外有一些画出美丽的效果的例子,由于篇幅见github: 
https://github.com/caibinterry/test/tree/caibin/%E8%B7%B3%E5%8A%A8%E7%9A%84%E8%8B%B1%E6%96%87%E5%90%8D




来自为知笔记(Wiz)