I need some help understanding what I’m doing wrong with my js code.
Basically I have a canvas and a particle that bounces around inside the canvas. What I want is for users to input data in a form and submit it, then the particle will start with their specified values.
The HTML body:
<canvas id="myCanvas" width="400" height="400"></canvas>
<form id="myForm" >
X Initial:
<input type="text" id="xInit" name="xInit" />
<br/>
Y initial:
<input type="text" id="yInit" name="yInit" />
<br/>
X Velocity:
<input type="text" id="xDir" name="xDir" />
<br/>
Y Velocity:
<input type="text" id="xDir" name="yDir" />
<br/>
Change:
<input type="submit" value="Submit">
</form>
The particle is it’s own class:
function particle(x, y, dX, dY) {
this.x = x;
this.y = y;
this.dX = dX;
this.dY = dY;
this.check = checkCollision;
}
I initialize the page and submit the form using jquery:
$(document).ready(function(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var HEIGHT = 400;
var WIDTH = 400;
var p1, xl, yl, xd, yd;
...More code...
$("form").submit(function(){
xl = +$("#xInit").val();
yl = +$("#yInit").val();
xd = +$("#xDir").val();
yd = +$("#xDir").val();
p1 = new particle(xl,yl,xd,yd);
init();
});
});
Then lastly, my init() function calls a function draw() to redraw the particle over a set Interval:
function init() {
draw();
alert(p1.x);
return setInterval(draw, 10);
}
So When I click submit everything works initially, it draws the particle 1 time and then it disappears forever. I believe it’s because the var p1, xl, yl, xd, yd; keeps re-declaring itself. Is there a way around this? Or a better way to set this up in general?
Many Thanks.
Update
The return false; part worked much appreciated
What’s happening is that your form is getting submitted when you click ‘Submit’. That refreshes the page, and your variables get reset.
You must return
falsein thesubmithandler to prevent that: