Add canvas to a page with javascript(使用 javascript 将画布添加到页面)
问题描述
我正在尝试使用 Javascript 将画布添加到原本没有画布的页面.我正在尝试执行以下操作:
I am trying to use Javascript in order to add a canvas to one page which originally does not have one. I am trying to do the following:
var canv=document.createElement("canvas");
canv.setAttribute("id", "canvasID");
alert(canv.id);
var c=document.getElementById("canvasID");
alert(c.id);
问题是第一个alert(canv.id) 结果是canvasID,而第二个alert 是未定义的,因为c 为null.
The problem is the the first alert(canv.id) results in canvasID, while the second alert is undefined because c is null.
谁能告诉我我做错了什么?
Can anybody tell me what am I doing wrong?
PS:代码设计为在 Greasemonkey 下运行,因此在 HTML 本身中添加画布及其 ID 不是一个可行的选择.
PS: the code is designed to run under Greasemonkey so adding the canvas and its ID in the HTML itself is not a viable option.
推荐答案
使用类似 Node.appendChild(child)
用于将其添加到 DOM:
Use something like Node.appendChild( child )
for adding it to the DOM:
var canv = document.createElement('canvas');
canv.id = 'someId';
document.body.appendChild(canv); // adds the canvas to the body element
document.getElementById('someBox').appendChild(canv); // adds the canvas to #someBox
<小时>
或者你可以使用element.innerHTML
:
document.body.innerHTML += '<canvas id="someId"></canvas>'; // the += means we add this to the inner HTML of body
document.getElementById('someBox').innerHTML = '<canvas id="someId"></canvas>'; // replaces the inner HTML of #someBox to a canvas
这篇关于使用 javascript 将画布添加到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 javascript 将画布添加到页面


基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01