为什么我的随机值几乎立即被覆盖?

时间:2016-11-11 00:17:37

标签: javascript css

我的代码出现问题。我尝试在随机位置生成对象,如drawHyperBall()getRandomIntX()getRandomIntY()所示。然而,正在发生的是随机值几乎立即被覆盖。我该如何解决这个问题?

以下代码:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height/2;
var ballRadius = 40;
var hBallRadius = 10;
var w = 5;
var hunger = 630;
var hypo = 0;
var hyper = 0;
var randomX;
var randomY;
var Keys = {
    	up: false,
        down: false,
        left: false,
        right: false
};
	
function drawBall() {
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = "#00FF00";
    ctx.fill();
    ctx.lineWidth= 3.5;
    ctx.stroke();
    ctx.closePath();
}
	
function drawConceBar() {
	ctx.strokeRect(100,930,630,30)
}
	
function drawHungerBar() {
	ctx.fillStyle = "#73591C";
	ctx.fillRect(1140,930,hunger,30)
	ctx.fillStyle = "black";
	ctx.strokeRect(1140,930,630,30)
}

function drawTitle() {
	ctx.fillStyle = "black";
	ctx.font = "120px Arial";
	ctx.fillText("Osmos.is",canvas.width/2 -210,120);
}
function drawBorder() {
	ctx.strokeRect(100,150,1670,730);
}
	
function getRandomIntX(minX,maxX) {
    return Math.floor(Math.random() * (maxX- minX + 1)) + minX;
}
function getRandomIntY(minY,maxY) {
    return Math.floor(Math.random() * (maxY - minY + 1)) + minY;
}

function drawHyperBall() {
	ctx.beginPath();
    ctx.arc(getRandomIntX(110, 1660), getRandomIntY(160, 720), hBallRadius, 0, Math.PI*2);
    ctx.fillStyle = "#FF0000";
    ctx.fill();
    ctx.closePath();
}
	
function draw() {
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	
	drawBall();
	
	drawBorder();
		
	drawTitle();
		
	drawConceBar();
		
	drawHungerBar();
		
	if(y > 830) {
	    y -= 5;
	}
	else if(y < 195) {
	    y += 5;
	}
	
	if(x < 150) {
		x += 5;
	}
	else if(x > 1720) {
		x -= 5;
	}
		
	if (Keys.up) {
	    y -= 5;
	}
	else if (Keys.down) {
	    y += 5;
	}

	if (Keys.left) {
	    x -= 5;
	}
	else if (Keys.right) {
	    x += 5;
	}
	
	if (hunger <= 0) {
		hunger += 1;
	}
	else {
		hunger -= 1;
	}
}
	
window.onkeydown = function(e) {
    var kc = e.keyCode;
    e.preventDefault();
    if      (kc === 37) Keys.left = true;  // only one key per event
    else if (kc === 38) Keys.up = true;    // so check exclusively
    else if (kc === 39) Keys.right = true;
    else if (kc === 40) Keys.down = true;
};
	
window.onkeyup = function(e) {
    var kc = e.keyCode;
    e.preventDefault();
    if      (kc === 37) Keys.left = false;
    else if (kc === 38) Keys.up = false;
    else if (kc === 39) Keys.right = false;
    else if (kc === 40) Keys.down = false;
};

setInterval(draw, 10);
setInterval(drawHyperBall, 1000);
<canvas id="myCanvas"></canvas>

1 个答案:

答案 0 :(得分:0)

我已经找到了问题所在。我正在清理所有的画布,所以我添加了一个新函数,它只能清除特定的东西。