不能多次使用功能

时间:2015-12-19 13:40:06

标签: javascript html5 canvas

由于某些原因,我似乎无法使用我的"播放器"功能不止一次所以这意味着我无法更新它的定位任何人都可以帮助解释原因吗?

继承我的代码:



var gridHeight = 1000, gridWidth = 1000, canvasHeight = 250, canvasWidth = 250, p = 0;
var currentPositionX = 0;
var currentPositionY = 0;

function buildGrid() {
	$("body").append("<canvas></canvas").css({
		height: canvasHeight, 
		width: canvasWidth, 
		border: "2px solid #000"
	});

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

    $("#canvas").css({height: canvasHeight, width: canvasWidth});

	for (var x = 0; x <= gridWidth; x += 40) {
        context.moveTo(0.5 + x + p, p);
        context.lineTo(0.5 + x + p, gridHeight + p);
    }


    for (var x = 0; x <= gridHeight; x += 20) {
        context.moveTo(p, 0.5 + x + p);
        context.lineTo(gridWidth + p,x + p);
    }

    context.strokeStyle = "black";
    context.stroke();

    function player(x, y, w, h, c) {
        this.x = x || 0;
        this.y = y || 0;
        this.h = h || 20;
        this.w = w || 40;
        this.c = c || "#FF0000";
    }

    function draw() {
        player = new player();
        context.fillstyle = player.c;
        context.fillRect(player.x,player.y,player.w,player.h);

        $("#right").on("click", function() {
            player.x += player.w;
            return player.x;
        })
    }

    setInterval(draw, 500)
}

$(document).ready(function() {
	buildGrid();
})
&#13;
* {
	padding: 0px;
	margin: 0px;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/game.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/game.js"></script>
</head>
<body style=" background: lightblue;">
	<canvas id="canvas"></canvas>
	<div id="controls">
		<button class="control" id="up">Up</button>
		<button class="control" id="left">Left</button>
		<button class="control" id="down">Down</button>
		<button class="control" id="right">Right</button>
		<button class="control" id="newPlayer">new player</button>
	</div>
</body>
</html>
&#13;
&#13;
&#13;

有人可以帮忙吗?我的目标是让按钮围绕网格移动方块。但它也具有可继承的属性,可用于后期的进一步功能。

2 个答案:

答案 0 :(得分:0)

player = new player();draw()中的执行结果覆盖你的函数定义。

如果您只是在此行前添加var,则播放器var将被限制在draw()的范围内,这可能是您想要的。

答案 1 :(得分:0)

jsFiddle:https://jsfiddle.net/j2q2qn2e/

javascript片段

-2

基本上你是每次抽奖创造一个新玩家的地方,但我所做的是将你的玩家“类”移到你的调用函数之外并在外面创建它,这样我们就可以创建一个基本玩家。我也搬了你的

function player(x, y, w, h, c) {
        this.x = x || 0;
        this.y = y || 0;
        this.h = h || 20;
        this.w = w || 40;
        this.c = c || "#FF0000";
    }
player = new player();

...

function draw() {

    context.fillstyle = player.c;
    context.fillRect(player.x,player.y,player.w,player.h);
}

setInterval(draw, 3)

在jQuery doc中准备就绪,因为它需要在此处分配事件而不是在draw函数内部,或者您将添加多个事件侦听器。所以你现在可以正确使用你的右键。