如何使用文本输入在HTML5画布中移动对象
How would one move an object in HTML5 canvas using text input?
我是HTML5画布的新手,到目前为止,我已经学会了如何通过键盘和鼠标处理用户输入。但是,您将如何通过检查文本输入来代替呢?例如,用户将输入文本说,walk 20,这会将对象向上移动 20 像素。完成此类任务的最佳方法是什么?
这是一个适合您的工作示例。 只需在文本输入中输入一个数字,然后按回车键即可。 试试看 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>
你得到输入的值,并在函数中使用它,就像其他动作一样:
document.getElementById('textFieldID').value
相关文章:
- css停止图像在滚动中移动
- 如何在react js中移动第二个组件
- 如何在JavaScript画布中移动此形状
- 如何使图像在画布中移动
- 在javascript中移动对象内部的元素
- 当DOM节点在DOM中移动时,如何阻止Firefox触发mouseleave
- 如何在小页面中移动折叠下方的渲染阻塞javascript
- 用鼠标在threejs场景中移动对象
- 使用箭头键在画布中移动形状
- 如何在kineticjs中移动图像
- 无法在 NG 网格中行的编辑字段中移动光标
- JavaScript 在 JSON 对象中移动如何判断元素是否存在
- 在循环中移动dom元素
- 在firefox上的滚动事件中移动元素
- 在jQuery中移动DOM元素(图层滑块)
- 使用jquery在正方形中移动文本
- 如何在Javascript中移动元素的旋转点
- 在剪裁的画布中移动所有图像
- 无法在场景中移动
- 通过在HTML中淡入淡出在图片中移动