So I have some code that bounces a ball around a canvas that allows users to change the size and color of the ball. What I want to add now is for them to have an input that changes the speed of the ball as well.
Here is the js
function draw(){
var canvas = document.getElementById('ball');
context= ball.getContext('2d');
//context.clearRect(150,50,750,750);
context.beginPath();
context.fillStyle="#0000ff";
context.arc(x,y,10,20,Math.PI*2,true);
context.closePath();
lineColor = document.getElementById('lineColor').value;
lineWidth = document.getElementById('lineWidth').value;
if (lineWidth)
{
context.lineWidth=lineWidth;
}
if (lineColor)
{
context.strokeStyle=lineColor;
context.stroke();
}
//context.fill();
if( x<0 || x>1000)
dx=-dx;
if( y<0 || y>1050)
dy=-dy;
x+=dx;
y+=dy;
}
//currently this line changes the speed
setInterval(draw,1);
Here is the html:
<html>
<body style="background-color:#FFDEAD;">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bouncing Ball Paint</title>
<body> Welcome to Paint Brush!
Before you begin: Please type in a color and width. Now sit back and enjoy the show.</body>
<body>
Ball Width: <input type="text" id="lineWidth"></input>
Ball Color: <input type="text" id="lineColor"></input>
Ball Speed X:<input type="text" id="speedx"></input>
<input type="button" value="Clear" onClick="window.location.href=window.location.href">
</body>
<body>
<h1>Bouncing a Ball</h1>
<div id="container">
<canvas id="ball" width="2050" height="2050"></canvas>
</div>
<script type="text/javascript"
src="balledit1.js"> </script>
</body>
</html>
Just how you're doing with the other settings, you'd make the 1 in your
setTimeout
based on the.value
of thespeedx
element (here I also set a fallback to 50)