Allowing the user to type text in a HTML5 Canvas g

2019-04-21 20:44发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

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

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

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 :)