Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing the user to type text in a HTML5 Canvas game

I'm trying to write my first HTML5 game using a combination of Canvas and the excellent KineticJS library and I've hit a bit of a wall early on.

What I want to do is ask the user to enter their name in a box in the game. Having done some research, i can't see any way of doing this outside getting a floating HTML element over that part of the canvas I'm using.

Is this correct?

Having grown up on a lot of Flash and web games, I'm sure each time I have to input a name or save file name, it's done directly into the game itself and it doesn't rely on the HTML to generate it?

Any advice on how to do this would be gratefully received.

like image 755
Craigeve Avatar asked Nov 17 '12 11:11

Craigeve


3 Answers

You can get a floating HTML element on the top of canvas using the following CSS technique.

http://css-tricks.com/absolute-positioning-inside-relative-positioning/

  • Make a wrapper div position: relative

  • Add canvas inside using position: absolute

  • Add other HTML controls inside using position: absolute

This applies for all HTML elements, not just canvas.

like image 128
Mikko Ohtamaa Avatar answered Oct 20 '22 09:10

Mikko Ohtamaa


Quick and dirty way:

var userInput = prompt('What is your name?');

It works, but certainly is not the prettiest way to do it. iOS actually has a quite nice prompt.

like image 21
pillar15 Avatar answered Oct 20 '22 09:10

pillar15


I know this is kind of old but....

Canvas Input is a great library that I use in my game:

enter image description here

As you can see, I can type in the box and have it display on the screen. It's easy to use:

var input = new CanvasInput({
    canvas: document.getElementById("ctx"),
    x: 0,
    y: 0,
    fontSize: 18,
    fontFamily: 'Arial',
    fontColor: '#212121',
    fontWeight: 'bold',
    width: 200,
    padding: 8,
    borderWidth: 1,
    borderColor: '#000',
    borderRadius: 3,
    onsubmit: function() {
        // your code here for submitting (when user presses enter)
    },
});

Disclaimer: I am in no way related to CanvasInput and am not receiving anything for this post :)

like image 28
sguan Avatar answered Oct 20 '22 10:10

sguan