javascript - Canvas - 未捕获的类型错误 : Cannot read property 'getContext' of null

标签 javascript jquery css html canvas

<分区>

我是 Canvas 的新手,正在 Codepen 上试用。我不断收到错误消息 - Uncaught TypeError: Cannot read property 'getContext' of null

我在 StackOverflow 上阅读了很多关于相同错误的类似问题,并尝试了提供的一些解决方案,但似乎都没有用。

这是因为某些答案似乎暗示 HTML 在 JavaScript 之前加载吗?不幸的是,我认为我无法在 Codepen 上进行更改。

我也尝试过将它包装在 $( document ).ready(function() {}); 中使用 jQuery 但这也不起作用。

基本上,我有这个 <canvas>元素 - <canvas id="mycanvas" class="orangeback"></canvas> 我正在尝试使用下面的 JavaScript 创建一个矩形和一些文本 -

function doRed() {
  var id1 = document.getElementById("mycanvas");
  id1.style.backgroundColor = "red";
  var canvas = document.getElementById("myCanvas");
  var context = canvas.getContext("2d");
  context.fillStyle = "purple";
  context.fillRect(10,10,60,60);

  context.fillStyle = "black";
  context.font = "30px Arial";
  context.text = "Hello";
}

Here's the link to my full code on JSFiddle

如果有人能指出我哪里出了问题,那将会很有帮助。谢谢!

最佳答案

您的脚本有错别字 myCanvas 应该改为 mycanvas。 您还查询了几次 Canvas ,您可以在变量中使用 document.getElementById() 的结果来最小化 dom 查询。

示例如下:

// cache result
var canvas = document.getElementById("mycanvas"),
context = canvas.getContext("2d");

function doRed() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  canvas.style.backgroundColor = "red";    
  context.fillStyle = "purple";
  context.fillRect(10,10,60,60);    
  context.fillStyle = "black";
  context.font = "30px Arial";
  context.fillText= "Hello";
}

function doBlue() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  canvas.style.backgroundColor = "blue";
}
h1 {
  color: red;
}

div {
  background-color: yellow;
}

#div1 {
  font-family: helvetica;
}

#div2 {
  font-size: 36px;
}

.orangeback {
  background-color: orange;
}

.yellowback {
  background-color: yellow;
}

.blueback {
  background-color: blue;
}

.pinkback {
  background-color: pink;
}

canvas {
  width: 200px;
  height: 100px;
}
<h1>Main Header</h1>
<canvas id="mycanvas" class="orangeback">
</canvas>
<input type="button" value="red" id="button2" onclick="doRed()">
<input type="button" value="blue" id="button3" onclick="doBlue()">

关于javascript - Canvas - 未捕获的类型错误 : Cannot read property 'getContext' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40099637/

相关文章:

javascript - 无法读取未定义的属性内部 html

jquery - 如何在 div 中将不同大小的幻灯片图像居中

jquery - 哪些控件触发了 Page.IsValid = false?

javascript - CSS/HTML、寻呼机、动态页面

html - 是否有为其他浏览器生成 "Linear Gradient"的工具?

javascript - 如何使 div 仅在跨度上跟随鼠标指针

javascript - 基于异步方法对数组进行排序

Javascript 根据类在选择框中选择选项

javascript - 用图像替换复选框并更新 onClick(可能是 jQuery?)

css - 在父 div 的中心对齐图片元素使图像左对齐