先介绍常用基础知识:
<script type="text/javascript">
window.onload()=function(){
var canvas=document.getElementById("canvas"); //获取元素
var context=canvas.getContext("2d");//绘制上下文环境,绘制所需接口
context.moveTo(100,100); //状态设置
context.lineTo(700,700); //状态设置
context.lineTo(100,700); //状态设置
context.lineTo(100,100); //状态设置
/*实心填充多边形*/
context.fillStyle="red";
context.fill();
/*线条绘制*/
context.lineWidth=5; //状态设置(线条粗度)
context.strokeStyle="#666" //状态设置(线条颜色)
context.stroke(); //绘制
/*如果设置另一条线颜色为紫色 lineTo strokeStyle,则包括上面线条也变为紫色,因为状态设置一直都在。此时需要beginPath (); closePath();将不同线条分隔开*/
}
</script>
七巧板绘制:
<script type="text/javascript">
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:"#a54c09"},
{p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:"#fa8ccc"},
{p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:"#f6ca29"}
]
window.οnlοad=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,ctxt){
ctxt.beginPath();
ctxt.moveTo(piece.p[0].x,piece.p[0].y);
for(j=1;j<piece.p.length;j++){
ctxt.lineTo(piece.p[j].x,piece.p[j].y);
}
ctxt.closePath();
ctxt.strokeStyle="#333";
ctxt.stroke();
ctxt.fillStyle=piece.color;
ctxt.fill();
}
</script>
计时器效果: