我一直在研究有关动态画布创建(1、2)的类似问题,但他们假设画布已经在 DOM 中。但是如果我想动态创建和绘制画布(换句话说,DOM 中没有画布或任何其他父元素)怎么办?
与此类似的东西(不起作用):
<!DOCTYPE HTML>
<html>
<head>
<title>canvas test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
for (var i = 0; i < 3; i++) {
var canvas = $('<canvas />').attr({
id: "canvas" + i,
width: 20,
height: 20
});
var ctx = $(canvas)[0].getContext('2d');
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, 20, 20);
$("#events").append("<tr><td>" + canvas[0].outerHTML + "</td></tr>");
}
});
</script>
</head>
<body>
<table id="events">
<tr>
<th>Canvas</th>
</tr>
</table>
</body>
</html>