HTML5之Canvas绘图(二) ——应用篇之七巧板

时间:2021-03-11 18:45:40

1.canvas绘制七巧板--

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>七巧板</title>
</head>
<body>
<canvas id="c1" style="border: 1px solid gray;"></canvas>
<script type="text/javascript">
var tangram = [
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"yellow"},
{p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:"pink"},
{p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:"purple"},
{p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:"blue"},
{p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:"red"},
{p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:"green"},
{p:[{x:400,y:800},{x:800,y:400},{x:800,y:800}],color:"lightblue"}
]; function draw(c,shape)
{ c.beginPath(); //开始绘制一个路径
c.moveTo(shape.p[0].x,shape.p[0].y);//移到要绘制的图形的第一个坐标处
c.fillStyle = shape.color;
for (var i = 1; i < shape.p.length; i++) //依次绘制到后续坐标
c.lineTo(shape.p[i].x,shape.p[i].y);
c.closePath(); //结束一个路径的绘制
c.fill();
}
window.onload = function(){
var canvas = document.getElementById("c1");
var context = canvas.getContext("2d");
canvas.width =800;
canvas.height = 800;
for (var i = 0; i < tangram.length; i++) {
draw(context,tangram[i]);
}
};
</script>
</body>
</html>

七巧板源码

HTML5之Canvas绘图(二) ——应用篇之七巧板

2.canvas绘制七巧板--小猫咪

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>七巧板--小猫</title>
</head>
<body> <canvas id="mycanvas"></canvas>
<script type="text/javascript"> (function(id){ var tangram=[ {p:[{x:520,y:40},{x:520,y:170},{x:595,y:110}],color:"#FDAD05"},
{p:[{x:595,y:110},{x:670,y:46},{x:670,y:170}],color:"#FC7861"},
{p:[{x:670,y:170},{x:595,y:110},{x:520,y:170},{x:595,y:246}],color:"#F2DE0C"},
{p:[{x:595,y:246},{x:432,y:390},{x:602,y:555}],color:"#CA9964"},
{p:[{x:595,y:246},{x:712,y:350},{x:600,y:465}],color:"#6CA4A7"},
{p:[{x:432,y:390},{x:430,y:620},{x:670,y:620}],color:"#F54C42"},
{p:[{x:175,y:528},{x:341,y:535},{x:430,y:620},{x:250,y:610}],color:"#9ECF00"} ] var canvas=document.getElementById(id); canvas.width=1090; canvas.height=880; var context=canvas.getContext('2d'); for(var i=0;i<tangram.length;i++)
{ context.beginPath(); context.moveTo(tangram[i].p[0].x,tangram[i].p[0].y); for(var j=1;j<tangram[i].p.length;j++){ context.lineTo(tangram[i].p[j].x,tangram[i].p[j].y);
} context.closePath(); context.fillStyle=tangram[i].color; context.strokeStyle=tangram[i].color; context.fill(); context.stroke();
} })('mycanvas') </script>
</body>
</html>

七巧板--小猫咪

HTML5之Canvas绘图(二) ——应用篇之七巧板