zafira.404
zafira.404

Reputation: 121

How would one move an object in HTML5 canvas using text input?

I am new to HTML5 canvas, and so far I have learned how to handle user input via keyboard and mouse. But how would you go by checking a text input instead? For example, a user would enter text saying, walk 20, which would move up an object by 20 pixels. What's the best way to accomplish such task?

Upvotes: 0

Views: 212

Answers (2)

nick
nick

Reputation: 1207

Here's a working example for you. Simply type a number into the text input and press enter. Try it at https://jsfiddle.net/w97zp61u/

<!DOCTYPE html>  
<html>
<head>
  <script>
    document.addEventListener('DOMContentLoaded',function(){
      var canvas = document.getElementsByTagName("canvas")[0], input =   document.getElementsByTagName("input")[0],
      ctx = canvas.getContext('2d'), dy;
      canvas.width =300, canvas.height =300, canvas.style.border ="1px solid black";
      input.style.width = 300+"px", input.style.display="block";
      var o ={
        init: function(){
          this.width = 10;
          this.height = 10;
          this.x =  (canvas.width-this.width)/2;
          this.y =  canvas.height-this.height;
          this.oy = this.y
        }
      }
      o.init()
      function draw(){
        o.y-= 1
        if(o.y>o.oy-dy){
          ctx.clearRect(0,0,canvas.width,canvas.height)
          ctx.fillRect(o.x,o.y,o.width,o.height)
          window.requestAnimationFrame(draw)
        }
        else{
          o.init()
          window.setTimeout(function(){
            ctx.clearRect(0,0,canvas.width,canvas.height)
            ctx.fillRect(o.x,o.y,o.width,o.height)
          },1000)
        }
      }
      function moveUp(e){
        if(e.keyCode === 13){
          dy = parseFloat(input.value);
          window.requestAnimationFrame(draw)
        }
      }
      document.addEventListener('keydown',moveUp)
    })
  </script>
</head>
<body>
  <div>
    <canvas></canvas>
    <input type ="text" placeholder ="type a number, then press enter">   </input>
  </div>
</body>
</html>

Upvotes: 2

Munsterlander
Munsterlander

Reputation: 1386

You get the value of the input and use it in your function like other movements:

document.getElementById('textFieldID').value

Upvotes: 0

Related Questions