我从控制台收到一条错误消息
这是js代码
控制台消息:未捕获的TypeError:无法读取null的属性'appendChild' 在file1.js:15
// Create the Canvas On Page
var myPageCanvas = document.createElement('canvas');
// Assign ID to this canvas
myPageCanvas.id = 'c';
myPageCanvas.width = 600;
myPageCanvas.height = 100;
myPageCanvas.style.display = 'block';
myPageCanvas.style.margin = '50px auto';
// Add the canvas to the Page
document.body.appendChild(myPageCanvas);
// Get Canvas information
var mycanvas = document.getElementById('c');
myContext = mycanvas.getContext('2');
// fill and style option
myContext.fillStyle = '#f00';
myContext.strokeStyle = '#00f';
myContext.lineWidth = 4;
myContext.font = '100px Arial';
// add the text
myContext.fillText('Elzero Web School', 50, 80);
答案 0 :(得分:2)
那不是你的问题。您的上下文未记录到myContext
变量中。为了证明这一点,您可以console.log(mycanvas)
≈,您将看到它实际上在那里。
更改:
myContext = mycanvas.getContext('2');
收件人:
myContext = mycanvas.getContext('2d');
答案 1 :(得分:0)
问题可能是您在主体之前加载了脚本。您应该在主体标签之后加载了脚本。例如:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Body content</h1>
</body>
<script>
var myPageCanvas = document.createElement('canvas');
// Assign ID to this canvas
myPageCanvas.id = 'c';
myPageCanvas.width = 600;
myPageCanvas.height = 100;
myPageCanvas.style.display = 'block';
myPageCanvas.style.margin = '50px auto';
// Add the canvas to the Page
document.body.appendChild(myPageCanvas);
// Get Canvas information
var mycanvas = document.getElementById('c');
myContext = mycanvas.getContext('2d');
// fill and style option
myContext.fillStyle = '#f00';
myContext.strokeStyle = '#00f';
myContext.lineWidth = 4;
myContext.font = '100px Arial';
// add the text
myContext.fillText('Elzero Web School', 50, 80);
</script>
</html>
或在加载身体后包含js文件:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Body content</h1>
</body>
<script src="path/to/file.js"></script>
</html>
答案 2 :(得分:0)
测试您的代码,我唯一遇到的错误是
postings
这是因为在上下文中,您应该使用2d而不是2d 之后一切正常。
重现错误的唯一方法是拥有一个不包含body标签的HTML文件,或者您可能在HTML结构中的body标签之前调用脚本。
这是示例工作。 https://jsfiddle.net/v4e0twd5/