Skip to content Skip to sidebar Skip to footer

Html/javascript Canvas Change Set Value To A User Input

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

Solution 1:

Just how you're doing with the other settings, you'd make the 1 in your setTimeout based on the .value of the speedx element (here I also set a fallback to 50)

<html>
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bouncing Ball Paint</title>
<style>
#ball{width:500px;height:500px; background:#CCC;}
</style>
</header>
<body style="background-color:#FFDEAD;">
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">
<h1>Bouncing a Ball</h1>
<canvas id="ball" width="500" height="500"></canvas>
<script>
var x=50;
var y=300;
var dx=10;
var dy=10;
function draw(){
   var ball = document.getElementById('ball');
   context= ball.getContext('2d');
   context.clearRect(0,0,ball.width,ball.height);
   lineColor = (document.getElementById('lineColor').value.length>0)?document.getElementById('lineColor').value:'#0000FF';
   lineWidth = (document.getElementById('lineWidth').value.length>0)?document.getElementById('lineWidth').value:'10';
   context.beginPath();
   context.fillStyle=lineColor;
   context.arc(x,y,lineWidth,20,Math.PI*2,true);
   context.closePath();
   if (lineWidth){
      context.lineWidth=lineWidth;
   }
   if (lineColor){
      context.strokeStyle=lineColor;
      context.stroke();
   }
   context.fill();
   if( x<0 || x>500)
      dx=-dx;
   if( y<0 || y>500)
      dy=-dy;
   x+=dx;
   y+=dy;
   fr = (document.getElementById('speedx').value>0)?document.getElementById('speedx').value:50;
   setTimeout(draw,fr);  
}
draw();
</script>
</body>
</html>

Post a Comment for "Html/javascript Canvas Change Set Value To A User Input"