canvas学习(一):七巧板
前几天在慕课网上学canvas的视频,因为老师讲的太好了让我觉得canvas很好玩,就跟着老师做了介个demo,这里记录一下。原视频连接如下:http://www.imooc.com/video/2435,有兴趣的同学可以去学学。
效果很简单,就不上图了,直接上代码吧:
1、html代码:
<body> <canvas id="myCanvas" style="border:1px solid #aaa;display:block;margin:50px;"> 当前浏览器不支持canvas,请换个浏览器试试。<!--这句话在支持canvas的浏览器中会被忽略,不支持的则会显示出来--> </canvas> </body>
2、JS代码:
window.onload=function(){ //1、获取canvas对象 var myCanvas = document.getElementById("myCanvas"); myCanvas.width=800;//设置画布的宽度 myCanvas.height=800;//设置画布的高度 //2、判断当前浏览器是否支持canvas if(myCanvas.getContext("2d")){ var context = myCanvas.getContext("2d");//获取canvas的上下文环境 //3、使用canvas进行绘制(七巧板) //3-1、定义数组,用来标记七巧板的坐标 var target=[ {p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"#CEFF68"}, {p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:"#66BDD0"}, {p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:"#F13D64"}, {p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:"#FAF61B"}, {p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:"#A793C4"}, {p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:"#F78FCE"}, {p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:"#F6C928"} ]; //3-2、循环各个数组进行绘制 for(var i=0;i<target.length;i++){ draw(target[i],context);//绘制 } }else{ alert("当前浏览器不支持canvas,请换个浏览器试试"); } } /** *该方法用来绘制图像 *@param piece:各个模块信息,包括坐标和填充颜色 *@parma cxt:canvas的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.lineWidth=3; cxt.strokeStype="black";//边框线 cxt.stroke(); }
相关推荐
大地飞鸿 2020-11-12
星星有所不知 2020-10-12
jinxiutong 2020-07-26
MIKUScallion 2020-07-05
songfens 2020-07-05
songfens 2020-06-11
songfens 2020-06-08
northwindx 2020-05-31
northwindx 2020-05-31
northwindx 2020-05-27
northwindx 2020-05-25
MIKUScallion 2020-05-25
jinxiutong 2020-05-10
xdyangxiaoromg 2020-05-10
大地飞鸿 2020-05-06
northwindx 2020-04-25