使用javascript将画布添加到页面 [英] Add canvas to a page with javascript

查看:644
本文介绍了使用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);

问题是第一个警报(canv.id)在canvasID中的结果,而第二个警报未定义,因为c为空。

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?

设计为在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将画布添加到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆