画布的元素在重绘后消失

时间:2018-03-25 21:26:34

标签: javascript canvas

我有一个画布,我试图用简单的文字游戏。

最初绘制的所有东西都是正确的,但是当我尝试重绘画布时,背景会消失。

HTML:

<canvas width="600" height="600" id="game-canvas"></canvas>

JS:

var width = 600;
var height = 400;
var canvas = document.getElementById("game-canvas");
var ctx = canvas.getContext("2d");
var scrambleWord = getScrambleOrder();

//object definitions
var game = {
    hasBegun:false,
    scrambleArr:scrambleWord.split(''),
    letterX:20,
    letterY:360
};

var startButton = {
    width:160,
    height:50,
    x:((height/2)),
    y:200,
    text:"Start!",
    color:"#90afc5"
};

//Event Listeners
function getMousePos(canvas, event) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}

function isInside(pos, rect){
    return pos.x > rect.x && pos.x < rect.x+rect.width && pos.y < rect.y+rect.height && pos.y > rect.y;
}


canvas.addEventListener('click', function(evt) {
    var mousePos = getMousePos(canvas, evt);

    if (isInside(mousePos,startButton)) {
        game.hasBegun = true;
    }else{
        console.log("clicked outside of button");
    }
}, false);

//Drawing
function draw() {
    //Background
    ctx.fillRect(0, 0, width, height);
    //Initial Screen
    if (!game.hasBegun) {
        ctx.fillRect(0, 0, width, height);
        ctx.font = "bold 50px verdana, sans-serif ";
        ctx.fillStyle = "#fff";
        ctx.fillText("Word Scramble!", 70, 80);
        ctx.font = "bold 20px verdana, sans-serif";
        ctx.fillText("Arrange the words as you go!", 150, 150);
        ctx.fillStyle = startButton.color;
        ctx.fillRect(startButton.x, startButton.y, startButton.width, startButton.height);
        console.log(startButton.x);
        ctx.fillStyle = "#fff";
        ctx.fillText(startButton.text, (startButton.x + 50), (startButton.y + 30));
    }

    //Game has begun - TAG BEGIN
    if (game.hasBegun) {
        for (var i = 0; i < game.scrambleArr.length; i++) {
            ctx.font = "bold 20px verdana, sans-serif ";
            ctx.fillStyle = "#fff";
            ctx.fillText(game.scrambleArr[i], game.letterX, game.letterY);
            game.letterX += 40;
        }
    }
}

setInterval(draw, 1000);

function getScrambleOrder() {
            var getScrambledWord = /[^=]*$/g;
            var url = window.location.href;
            var finalWord = url.match(getScrambledWord);
            return finalWord[0];
}

为什么背景不亮时开始按钮会保留在屏幕上?

我尝试将绘制黑色屏幕的位置移动到绘制按钮的if语句中,但它仍然消失。

看起来一切都是最初绘制的,然后除了开始按钮之外的所有内容都会在重绘一次画布后消失。

Here is a jsfiddle that demonstrates the problem.

0 个答案:

没有答案