问答详情
源自:2-2 绘制直线、多边形和七巧板

不知道为什么一直显示不出来,还报错?

var trm=new Array([
{p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"#CCFF33"},
{p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:"#33CCFF"},
{p:[{x:800,y:0},{x:800,y:400},{x:600,y:600}],color:"#FF0000"},
{p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:"#FFFF00"},
{p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:"#9900FF"},
{p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:"#FF77FF"},
{p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:"#FFBB66"}
]);
//标准的画布定义兼容性初始化
window.onload=function(){
var canvas=document.getElementById("canvas");
canvas.width=800;
canvas.height=800;
if (canvas.getContext) {
var ctx=canvas.getContext("2d")
} else{
alert('该浏览器不支持canvas,请您更换浏览器后重试')
}
for (var i=0;i<trm.length;i++) {
draw(trm[i],ctx);
}
function draw(demo,ctx){
ctx.beginPath();
ctx.moveTo(demo.p[0].x,demo.p[0].y);
for (var j=1;j<demo.p.length;j++) {
ctx.lineTo(demo.p[j].x,demo.p[j].y);
}
ctx.fillStyle="demo.color";
ctx.fill();
}



提问者:Lucifershine 2016-10-28 12:32

个回答

  • 慕斯卡3531659
    2016-11-10 23:57:19

    // 七巧板的各个颜色色块

    var trm=[

    {p:[{x:0,y:0},{x:800,y:0},{x:400,y:400}],color:"#CCFF33"},

    {p:[{x:0,y:0},{x:400,y:400},{x:0,y:800}],color:"#33CCFF"},

    {p:[{x:800,y:0},{x:800,y:400},{x:600,y:600},{x:600,y:200}],color:"#FF0000"},

    {p:[{x:600,y:200},{x:600,y:600},{x:400,y:400}],color:"#FFFF00"},

    {p:[{x:400,y:400},{x:600,y:600},{x:400,y:800},{x:200,y:600}],color:"#9900FF"},

    {p:[{x:200,y:600},{x:400,y:800},{x:0,y:800}],color:"#FF77FF"},

    {p:[{x:800,y:400},{x:800,y:800},{x:400,y:800}],color:"#FFBB66"}

    ];

    window.onload = function(){

    var canvas = document.getElementById('canvas');

    canvas.height = 900;

    canvas.width = 1024;

    var context = canvas.getContext("2d");


    for(var i=0;i<trm.length;i++){

    draw(trm[i],context);

    }

    }

    function draw(demo,ctx){

    ctx.beginPath();

    ctx.moveTo(demo.p[0].x,demo.p[0].y);

    for(var j=1;j<demo.p.length;j++){

    ctx.lineTo(demo.p[j].x,demo.p[j].y);

    }

    ctx.fillStyle = demo.color;

    ctx.fill();

    }


  • DeadSnow
    2016-10-28 15:06:38

    1. 你少了一个分号;

    2. trm = [] 和 new Array()定义不一样。new Array()是创建一个array 的object。

    3. ctx.fillStyle="demo.color";不要加引号

    同学你这个基础有点差,要多注意些细节问题。