矩形没有出现在js画布中

时间:2015-11-16 21:47:54

标签: javascript html5 function canvas rect

我有一个我无法解决的破坏性问题。

JS画布正在拧紧播放器函数表达式旁边的一个矩形。这是播放器代码:

var menuSwitch = 0;
var pocx = 210;
var pocy = 20;
var switch1;
var lvlSwitch = 1;
var spd = 10;
var mx,my;
var pl = pl();
function pl(){
return{
    draw: function(){
        //draw the player
        ctx.clearRect(0,0,w,h);//clears so the player doesn't "drag"
        ctx.beginPath();
        ctx.fillStyle = 'blue';
        ctx.arc(pocx, pocy, 10, 0, Math.PI*2, true); 
        ctx.closePath();
        ctx.fill();

        //move the player
        if(switch1 == 0){
            pocx = 210;
            pocy = 20;
        }else if(switch1 == 1){
            pocy -= spd;
        }else if(switch1 == 2){
            pocx -= spd;   
        }else if(switch1 == 3){
            pocy += spd;
        }else if(switch1 == 4){
            pocx += spd;
        }

        //rect bounding the player
        if(pocx < 5){//since half of the diameter of the player is 5, the edge of the circle "bounces"
            switch1 = 4;
        }
        if(pocy < 5){
            switch1 = 3;   
        }
        if(pocx > w){
            switch1 = 2;
        }
        if(pocy > h){
            switch1 = 1;
        }
    }
};
}

画布是420乘420. paint()函数每次显示30毫秒setInterval显示在这里:

function paint(){
//pl.draw();
if(menuSwitch == 0){
    ctx.fillStyle = 'black';
    ctx.fillRect(0,0,w,h);
    ctx.fillStyle = 'skyblue';
    ctx.fillRect(20,20,380,50);
    ctx.font = 'normal 30pt Arial';
    ctx.fillStyle = 'lime';
    ctx.fillText("Math Path",105,60);
    ctx.fillStyle = 'skyblue';
    ctx.fillRect(105,150,210,25);//105+210=315
    ctx.font = 'normal 15pt Arial';
    ctx.fillStyle = 'lime';
    ctx.fillText("Start",170,170);
}
if(menuSwitch == 1){
ctx.fillStyle = 'blue';
ctx.fillRect(300,20,120,20);
pl.draw();

}
} 

但是,我专注于if语句中menuSwitch == 1的位置。你可以看到我正在调用播放器。播放器显示,但不显示矩形。请帮忙? :(

有用的链接:Canvas Tutorial

如果您需要Html代码:

Jsfiddle

1 个答案:

答案 0 :(得分:0)

这是因为你在播放器功能中调用了ctx.fillRect(300,20,120,20);。修复它,删除该行并将其添加到您的绘图功能,如:

function paint() {
    ctx.clearRect(0, 0, w, h); //clears so the player doesn't "drag"
    //pl.draw();
    if (menuSwitch == 0) {
        ctx.fillStyle = 'black';
        ctx.fillRect(0, 0, w, h);
        ctx.fillStyle = 'skyblue';
        ctx.fillRect(20, 20, 380, 50);
        ctx.font = 'normal 30pt Arial';
        ctx.fillStyle = 'lime';
        ctx.fillText("Math Path", 105, 60);
        ctx.fillStyle = 'skyblue';
        ctx.fillRect(105, 150, 210, 25); //105+210=315
        ctx.font = 'normal 15pt Arial';
        ctx.fillStyle = 'lime';
        ctx.fillText("Start", 170, 170);
    }
    if (menuSwitch == 1) {
        ctx.fillStyle = 'blue';
        pl.draw();
        ctx.fillRect(300, 20, 120, 20);
    }
}

小提琴显示示例:https://jsfiddle.net/22w9j3p0/