h5 canvas元素,怎么解决Uncaught TypeError: Cannot read property 'getContext' of null?

Zimmy 113个月前 提问 源自: HTML5|HTML5 画布(Canvas)
0

代码如下: <script type="text/javascript"> var c = document.getElementById('myCanvas'); var ctx = c.getContext('2d'); ctx.fillStyle('blue'); ctx.fillRect(10,20,110,50); </script>

  • 1
    ciga 113个月前 回答

    变量c是null对象。

    1. 检查第一行代码,确认你的c变量被正确赋值:

    var c = document.getElementById("myCanvas");
    console.log(c);

    2. 检查你的浏览器兼容性,参考下面连接的Browser Compatibility节:

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext


    最佳答案
  • 0
    未鸣 113个月前 回答
    把代码放在window.onload里面,或者等html加载完成之后再运行js