我是HTML5画布的新手,到目前为止,我已经学会了如何通过键盘和鼠标处理用户输入。但是,如何通过检查文本输入来改变?例如,用户将输入文本说,步行20,这将使对象向上移动20个像素。完成此类任务的最佳方法是什么?
答案 0 :(得分:2)
这是一个适合您的工作示例。只需在文本输入中键入一个数字,然后按Enter键。在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>
答案 1 :(得分:0)
您可以获得输入的值,并像其他动作一样在函数中使用它:
document.getElementById('textFieldID').value