如何使用JavaScript向Canvas元素中添加HTML元素?
在Canvas上添加可交互输入区域的实现方案
通过以下代码,你能在Canvas区域内距顶部和左侧各100px的位置得到一个输入区域,相关调整和扩展方式如下:
- 更改输入区域位置:只需修改代码中
input.style.left和input.style.top的数值即可 - 添加其他HTML元素:在脚本的
createElement方法中传入元素名称(如button、div),就能创建对应的HTML元素并添加到页面中
<!-- HTML CONTENT--> <body> <canvas id="canvas" style="background-color:rgb(171, 171, 250)"></canvas> <!--JavaScript CONTENT--> <script> // 适配高DPI的Canvas区域设置 var res = window.devicePixelRatio || 1, scale = 1 / res; var canvas = document.querySelector("#canvas"); var ctx = canvas.getContext('2d'); canvas.height = window.innerHeight * res; canvas.width = window.innerWidth * res; canvas.style.height = window.innerHeight + 'px'; canvas.style.width = window.innerWidth + 'px'; ctx.scale(res, res); // 在Canvas上方添加input输入框 function addInput() { var input = document.createElement('input'); input.type = 'text'; input.style.position = 'absolute'; input.style.left = '100px'; // 输入框的X轴位置 input.style.top = '100px'; // 输入框的Y轴位置 input.style.background = 'white'; input.style.width = '75px'; input.style.fontWeight = 'bolder'; document.body.appendChild(input); input.focus(); } addInput(); </script> <!--JavaScript End Here--> </body>
内容的提问来源于stack exchange,提问作者Basavaraj Kittali
相关产品推荐
相关产品推荐

