在慕课网有一节讲的是用canvas画七巧板,自己回来重新做了一下。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tangram</title>
</head>
<body>
<canvas id="canvas" width="400" height="400" style="border:1px solid #000;">
浏览器版本不支持html5
</canvas>
<script>
//七巧板对象,定义了坐标及颜色
var tangram = [
{p:[{x:0,y:0},{x:0,y:400},{x:200,y:200}],color:"#A4C400"},
{p:[{x:200,y:200},{x:0,y:400},{x:400,y:400}],color:"#0050EF"},
{p:[{x:300,y:300},{x:400,y:200},{x:400,y:400}],color:"#6A00FF"},
{p:[{x:300,y:100},{x:100,y:100},{x:200,y:200}],color:"#E51400"},
{p:[{x:200,y:0},{x:400,y:0},{x:400,y:200}],color:"#E3C800"},
{p:[{x:0,y:0},{x:100,y:100},{x:300,y:100},{x:200,y:0}],color:"#6D8764"},
{p:[{x:300,y:100},{x:400,y:200},{x:300,y:300},{x:200,y:200}],color:"#F472D0"}
];
window.onload = function(){
console.log("author:AliceCheck;http://my.csdn.net/alicecheck");
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
for(var i=0,len=tangram.length; i < len; i++ ){
getTangram(tangram[i],context);
}
}
//画出每一个块
function getTangram(piece,context){
context.beginPath();
context.moveTo(piece.p[0].x,piece.p[0].y);
for(var i = 1,len=piece.p.length; i < len; i++){
context.lineTo(piece.p[i].x,piece.p[i].y);
}
context.fillStyle=piece.color;
context.fill();
context.closePath();
}
</script>
</body>
</html>
东西很简单的
效果图