沐可的博客 沐可的博客

用canvas标签画纸鹤

in HTML5 read (154) 文章转载请注明来源!

效果图:

思路分析:纸鹤可以分解为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
                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
                ctx.lineTo(MARGIN_LEFT+array.piece[i].x,MARGIN_TOP+array.piece[i].y);
            }
            ctx.fillStyle=array.color;
            ctx.fill();
            ctx.closePath();
         }
canvas
最后由沐可修改于2017-09-19 22:09
发表新评论
博客已萌萌哒运行
© 2017 由 Typecho 强力驱动.Theme by Yodu赣ICP备15009801号
PREVIOUS NEXT
雷姆
拉姆