HTML5 动态创建 Canvas [英] HTML5 Dynamically create Canvas
本文介绍了HTML5 动态创建 Canvas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我有一个关于使用 javascript 动态创建画布的问题.
Hi there I have a question about dynamically creating a canvas using javascript.
我创建了一个这样的画布:
I create a canvas like this:
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 768;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";
但是当我尝试定位它时,我得到一个 null
值:
but when I try to locate it, I get a null
value:
cursorLayer = document.getElementById("CursorLayer");
我做错了吗?有没有更好的方法来使用 JavaScript 创建画布?
Am I doing it wrong? Is there a better way to create a canvas using JavaScript?
推荐答案
问题是你没有在文档正文中插入画布元素.
The problem is that you do not insert your canvas element in the document body.
只需执行以下操作:
document.body.appendChild(canvas);
示例:
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 768;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";
var body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
cursorLayer = document.getElementById("CursorLayer");
console.log(cursorLayer);
// below is optional
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(255, 0, 0, 0.2)";
ctx.fillRect(100, 100, 200, 200);
ctx.fillStyle = "rgba(0, 255, 0, 0.2)";
ctx.fillRect(150, 150, 200, 200);
ctx.fillStyle = "rgba(0, 0, 255, 0.2)";
ctx.fillRect(200, 50, 200, 200);
这篇关于HTML5 动态创建 Canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文