用JS将画布插入DIV中

3
我有这段代码。
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
let windowWidth = canvas.width = window.innerWidth;
let windowHeight = canvas.height = window.innerHeight;
canvas.id = 'canvas';
document.body.insertBefore(canvas, document.body.firstChild);

问题是我无法将它添加到一个div中,例如:<div class="ip_first_block">画布应该在这里</div>。我刚开始学习js,所以大部分时间都在组合和编辑代码片段。这就是我需要更改的部分,但我找不到正确的方法。
document.body.insertBefore(canvas, document.body.firstChild);

这是我的一次尝试...
var canvas = document.createElement('canvas');
var firstblock = document.getElementsById('ifb');
var context = canvas.getContext('2d');
var windowWidth = canvas.width = window.innerWidth;
var windowHeight = canvas.height = window.innerHeight;
canvas.id = 'canvas';
firstblock.innerHTML += canvas;
1个回答

1

canvas是一个元素,而不是一个字符串。您应该使用正确的API将其附加为子级: firstblock.appendChild(canvas)

document.addEventListener('DOMContentLoaded', () => {
  var canvas = document.createElement('canvas')

  var container = document.querySelector('.ip_first_block')

  container.appendChild(canvas)

})

非常感谢。它有效。我可以在8分钟内接受答案。 - JGeorgeJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接