您好我正在尝试使用javascripts canvas元素制作一个非常简单的游戏。我在画布上绘制了一个矩形,我希望当用户单击按钮但它不能正常工作时它会在画布上移动。
这是我的HTML:
<style>
canvas {
border: 1px solid black;
height: 300px;
width:500px;
}
</style>
</head>
<body>
<button id = "play">Click to play</button>
</body>
我的javascript:
$( document ).ready(function() {
var x = document.createElement("CANVAS");
var ctx = x.getContext("2d");
ctx.fillStyle = "#FF0000";
var x1 = 10;
var y = 10;
ctx.fillRect(x1, y, 80, 10);
document.body.appendChild(x);
var Game = {stopped:true};;
Game.draw = function() {
ctx.fillRect(x1, y, 80, 10);
};
Game.update = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x1 = x1+5;
};
Game.run = function() {
Game.update();
Game.draw();
};
$("#play").click(function() {
Game.stopped = false;
while (!Game.stopped){
Game.run();
}
});
});
答案 0 :(得分:1)
您的脚本中存在多个问题。
canvas
的变量x
所以
var interval;
$("#play").click(function () {
Game.stopped = false;
interval = setInterval(Game.run, 5);
});
$("#stop").click(function () {
Game.stopped = true;
clearInterval(interval);
});
演示:Fiddle
答案 1 :(得分:1)
还有另一个简单的工具:
$(document).ready(function () {
var canvas = document.createElement("CANVAS");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
var x1 = 10;
var y = 10;
ctx.fillRect(x1, y, 80, 10);
document.body.appendChild(canvas);
var Game = {stopped: true};
;
Game.draw = function () {
ctx.fillRect(x1, y, 80, 10);
};
Game.update = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
x1 = x1 + 5;
};
Game.run = function () {
Game.update();
Game.draw();
};
$("#play").click(function () {
Game.stopped = false;
// while (!Game.stopped) {
// Game.run();
// }
if(!Game.stopped){
setInterval(Game.run,1000);
}
});
});
对于动画,如果你想获得更好的表现,最好使用Plunker。