here is my html:
\n\n<style>\ncanvas {\nborder: 1px solid black;\nheight: 300px;\nwidth:500px;\n}\n</style>\n</head>\n<body>\n\n<button id = \"play\">Click to play</button>\n</body>\n
\n\nMy javascript:
\n\n$( document ).ready(function() {\nvar x = document.createElement(\"CANVAS\");\nvar ctx = x.getContext(\"2d\");\nctx.fillStyle = \"#FF0000\";\nvar x1 = 10;\nvar y = 10;\nctx.fillRect(x1, y, 80, 10);\ndocument.body.appendChild(x);\n\nvar Game = {stopped:true};;\n\nGame.draw = function() { \n ctx.fillRect(x1, y, 80, 10);\n};\nGame.update = function() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n x1 = x1+5;\n\n};\n\nGame.run = function() {\n Game.update();\n Game.draw();\n};\n\n$(\"#play\").click(function() {\n\n Game.stopped = false;\n while (!Game.stopped){\n Game.run(); \n }\n\n\n});\n});\n
\n","author":{"@type":"Person","name":"user4348719"},"upvoteCount":0,"answerCount":2,"acceptedAnswer":null}}Reputation: 351
Hi I'm trying to make a very simple game using javascripts canvas element. I have a rectangle thats drawn on the canvas and I would like for it to move across the canvas when user clicks a button but its not working.
here is my html:
<style>
canvas {
border: 1px solid black;
height: 300px;
width:500px;
}
</style>
</head>
<body>
<button id = "play">Click to play</button>
</body>
My 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();
}
});
});
Upvotes: 0
Views: 38
Reputation: 1785
There is another simple implement:
$(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);
}
});
});
For animation, it's better to use Window.requestAnimationFrame(), if you want to get a better performance.
Upvotes: 1
Reputation: 388436
There are multiple problems in your script.
canvas
it is x
So
var interval;
$("#play").click(function () {
Game.stopped = false;
interval = setInterval(Game.run, 5);
});
$("#stop").click(function () {
Game.stopped = true;
clearInterval(interval);
});
Demo: Fiddle
Upvotes: 1