不满足于CSS对颜色的控制,使用html5画布功能绘制了一张漂亮的五彩图片,以下代码,复制粘贴进一个格式为HTML的文档即可见。
<canvas id="canvas"style="border:5px solid #ccc;display: block;margin:0 auto;"></canvas>
1 <script type="text/javascript"> 2 var tangtam=[ 3 {p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"#caff67"}, 4 {p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:"#67becf"}, 5 {p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:"#ef3d61"}, 6 {p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:"#f9f51a"}, 7 {p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:"#a594c0"}, 8 {p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:"#fa8ecc"}, 9 {p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:"#f6ca29"} 10 ] 11 window.onload=function(){ 12 var canvas=document.getElementById("canvas"); 13 // 定义画布大小必须申明变量后就进行设置 14 canvas.width = 800; 15 canvas.height = 800; 16 17 var context=canvas.getContext("2d"); 18 for(var i=0;i<tangtam.length;i++){ 19 draw(tangtam[i],context); 20 } 21 22 //判断浏览器对canvas的支持 canvas是基于状态的绘制 23 // var canvas=document.getElementById("canvas"); 24 // if(canvas.getContext("2d")){ 25 // var canvas=canvas.getContext("2d"); 26 // }else{ 27 // alert("当前浏览器不支持canvas,请更换浏览器再尝试") 28 // } 29 } 30 function draw(piece,cxt){ 31 cxt.beginPath(); 32 cxt.moveTo(piece.p[0].x,piece.p[0].y); 33 for(var i=1;i<piece.p.length;i++){ 34 cxt.lineTo(piece.p[i].x,piece.p[i].y); 35 } 36 cxt.closePath(); 37 cxt.fillStyle=piece.color; 38 cxt.fill(); 39 } 40 </script>