gpt4 book ai didi

javascript - 用js在div里面插入 Canvas

转载 作者:行者123 更新时间:2023-11-29 23:24:04 25 4
gpt4 key购买 nike

我有这部分代码

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">CANVAS SHOULD BE HERE</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;

最佳答案

canvas 是一个元素而不是字符串。您应该使用适当的 API 将其附加为子项:firstblock.appendChild( Canvas )

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

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

container.appendChild(canvas)

})

关于javascript - 用js在div里面插入 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com