Allowing the user to type text in a HTML5 Canvas game

戏子无情 提交于 2019-12-05 03:41:39

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!