You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 23:05:30