gpt4 book ai didi

javascript - canvas.getContext ("2d");不工作

转载 作者:行者123 更新时间:2023-12-01 02:42:34 24 4
gpt4 key购买 nike

我收到以下错误

Error: Uncaught TypeError: Cannot read property 'innerHTML' of null at script.js:1

我已经尝试了所有我能想到的方法,但没有任何效果。

var canvas = document.getElementById("can").innerHTML;
var ctx = canvas.getContext("2d");
ctx.fillStyle = ("green");
ctx.fillRect(0, 0, 300, 200);
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas
</body>
</html>

最佳答案

1。使用 Canvas 时出现脚本错误

Use var canvas = document.getElementById("can");

Not var canvas = document.getElementById("can").innerHTML();

参见W3C - Canvas

2。文档准备好后添加事件监听器,然后执行脚本

参见W3C - DOM Event Listener example

function doSomething() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext('2d');
/*
another scripts...
*/
}

window.addEventListener('onload', doSomething, false);

关于javascript - canvas.getContext ("2d");不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47457626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com