用canvas标签画纸鹤

效果图:

纸鹤

思路分析:纸鹤可以分解为10不同颜色块组合而成,利用canvas画多边形,并填充不同颜色

1. 定义一个 magic 的数组,该数组中包含各个颜色块的坐标和颜色值,并定义画布的长宽和margin值

var magic=[
{piece:[{x:52,y:57},{x:237,y:0},{x:295,y:158}],color:"#a4e2c6"},
{piece:[{x:237,y:0},{x:357,y:58},{x:295,y:158}],color:"#789262"},
{piece:[{x:357,y:58},{x:457,y:58},{x:408,y:165}],color:"#bddd22"},
{piece:[{x:457,y:58},{x:485,y:114},{x:440,y:96}],color:"#96ce54"},
{piece:[{x:357,y:58},{x:408,y:165},{x:157,y:283},{x:295,y:158}],color:"#057748"},
{piece:[{x:440,y:96},{x:453,y:101},{x:424,y:185},{x:408,y:165}],color:"#50616d"},
{piece:[{x:408,y:165},{x:424,y:185},{x:309,y:238},{x:315,y:208}],color:"#eaff56"},
{piece:[{x:315,y:208},{x:269,y:454},{x:157,y:283}],color:"#ca6924"},
{piece:[{x:93,y:85},{x:103,y:78},{x:295,y:158},{x:259,y:158}],color:"#6e511e"},
{piece:[{x:259,y:158},{x:295,y:158},{x:157,y:283}],color:"#fff2da"}
]
var WINDOW_WIDTH=535;
var WINDOW_HEIGHT=455;
var MARGIN_LEFT=0;
var MARGIN_TOP=0;

2. 利用for循环将数组中的多边形分别遍历画出

window.onload=function(){
var canvas=document.getElementById('canvas');
var context=canvas.getContext("2d");
canvas.width=WINDOW_WIDTH;
canvas.height=WINDOW_HEIGHT;
for(var i=0;i<magic.length;i++){
draw(magic[i],context);}
}

3. 定义draw函数,画出多边形并填充不同颜色值

function draw(array,ctx){    //传入的array为数组的索引值,例如传入margin[5]
ctx.beginPath();
ctx.moveTo(MARGIN_LEFT+array.piece[0].x,MARGIN_TOP+array.piece[0].y);
for(var i=0;i<array.piece.length;i++){
ctx.lineTo(MARGIN_LEFT+array.piece[i].x,MARGIN_TOP+array.piece[i].y);
}
ctx.fillStyle=array.color;
ctx.fill();
ctx.closePath();
}

2019-12-06 06:45:24