<script>
var tangram=[
{p:[{x:0,y:0},{x:300,y:0},{x:150,y:150}],color:"#caff67"},
{p:[{x:0,y:0},{x:150,y:150},{x:0,y:300}],color:"#67becf"},
{p:[{x:300,y:0},{x:300,y:150},{x:225,y:225},{x:225,y:75}],color:"#ef3d61"},
{p:[{x:225,y:75},{x:225,y:225},{x:150,y:150}],color:"#f9f51a"},
{p:[{x:150,y:150},{x:225,y:225},{x:150,y:300},{x:75,y:225}],color:"#a594c0"},
{p:[{x:75,y:225},{x:150,y:300},{x:0,y:300}],color:"#fa8ecc"},
{p:[{x:300,y:150},{x:300,y:300},{x:150,y:300}],color:"#f6ca29"},
];
window.onload=function(){
var canvas=document.getElementById("canvas");
if(canvas.getContext("2d")){
var context=canvas.getContext("2d");}else{
alert("当前浏览器不支持canvas,请更换浏览器后再试");
}
for(var i=0;i<tangram.length;i++){
draw(tangram[i],context);
}
function draw(piece,cxt){
cxt.beginPath();
cxt.moveTo(piece.p[0].x,piece.p[0].y);
for(var i=0;i<piece.p.length;i++){
cxt.lineTo(piece.p[i].x,piece.p[i].y);
}
cxt.closePath();
cxt.fillStyle=piece.color;
cxt.fill();
}
}
</script>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>xxxx</title> <script> var tangram=[ {p:[{x:0,y:0},{x:300,y:0},{x:150,y:150}],color:"#caff67"}, {p:[{x:0,y:0},{x:150,y:150},{x:0,y:300}],color:"#67becf"}, {p:[{x:300,y:0},{x:300,y:150},{x:225,y:225},{x:225,y:75}],color:"#ef3d61"}, {p:[{x:225,y:75},{x:225,y:225},{x:150,y:150}],color:"#f9f51a"}, {p:[{x:150,y:150},{x:225,y:225},{x:150,y:300},{x:75,y:225}],color:"#a594c0"}, {p:[{x:75,y:225},{x:150,y:300},{x:0,y:300}],color:"#fa8ecc"}, {p:[{x:300,y:150},{x:300,y:300},{x:150,y:300}],color:"#f6ca29"}, ]; window.onload=function(){ var canvas=document.getElementById("canvas"); if(canvas.getContext("2d")){ var context=canvas.getContext("2d");}else{ alert("当前浏览器不支持canvas,请更换浏览器后再试"); } for(var i=0;i<tangram.length;i++){ draw(tangram[i],context); } function draw(piece,cxt){ cxt.beginPath(); cxt.moveTo(piece.p[0].x,piece.p[0].y); for(var i=0;i<piece.p.length;i++){ cxt.lineTo(piece.p[i].x,piece.p[i].y); } cxt.closePath(); cxt.fillStyle=piece.color; cxt.fill(); } } </script> </head> <body> <canvas id="canvas" width="500px" height="500px"></canvas> </body> </html>
你的代码 我什么也没有改,是没有问题。