使用 javascript 将画布添加到页面

编程入门 行业动态 更新时间:2024-10-22 16:33:39
本文介绍了使用 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 将画布添加到页面

本文发布于:2023-10-04 09:17:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1467143.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:画布   页面   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!