【问题标题】:Cannot read property 'getContext' of null无法读取 null 的属性“getContext”
【发布时间】:2014-03-19 13:34:56
【问题描述】:

我有一个按钮,点击后执行此功能。此代码是在画布元素上绘制一条线,使用 PDF.JS 在网页上呈现 PDF 文件。但我收到一个错误“未捕获的 TypeError:无法读取属性 'getContext' of null”。我该怎么办。

function abc()
{
alert("msg");
var c=document.getElementById("canvas1");
alert(c);
var ctx= c.getContext('2d');
alert(ctx);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();
}

【问题讨论】:

  • 您有 ID 为 canvas1 的元素吗?该错误强烈建议您不要!
  • 如果在使用它的脚本标签下定义了 canvas1,你也会遇到同样的错误

标签: javascript canvas pdf.js


【解决方案1】:

首先,你应该检查null:

var c = document.getElementById("canvas1");
if (c != null) {
  // proceed
} else {
  // a problem: what can you do about it?
}

其次,确保你有一个元素canvas1 - 如果它存在,那么c 不应该是null;如果它不存在,则代码和内容之间存在差异,您需要决定在这种情况下应该发生什么,如果它应该永远发生,那么它是例外的,也许你想要引发错误,或您自己指定的消息,或其他内容。

【讨论】:

  • 我正在使用 pdf.js 在我的网站上呈现 pdf 文件。我无法访问在其上呈现 pdf 文件的画布。此代码是程序的一部分。我已经尝试过您的解决方案,显然“c”为空。如果您了解 pdf.js,请帮助我。感谢您的帮助。
  • 如果cnull,那么您没有带有id="canvas1" 的画布。将其更改为画布的 ID。
【解决方案2】:

我在 2D 中使用带有大写“D”的var ctx= c.getContext('2D');,这是不正确的。它应该是 2d 中的小写“d”。我意识到这是一个非常简单的错误,但它把我带到了这里。希望我没有其他人开始在这么简单的事情上拔毛。

【讨论】:

  • 这个答案刚刚救了我的命。我很困惑,对于这样一个简单的错误,没有真正的方法来检测它是令人失望的。
【解决方案3】:

检查脚本的位置。我已经将它包含在 <head> 部分中,很明显,它甚至在将其附加到 DOM 之前就试图找到 canvas 元素。从而给出undefinednull 错误。

【讨论】:

    【解决方案4】:

    据我所知,您的代码可以正常工作(刚刚添加了以下 HTML):

    <button onclick="abc()">button</button>
    <canvas id="canvas1" height="300" width="300"/>
    

    http://jsfiddle.net/qBHRg/

    【讨论】:

      【解决方案5】:

      假设您的警报报告您有对画布和上下文的有效引用:

      警报#1:HTMLCanvasElement

      警报#2:CanvasRenderingContext2D(或您的浏览器版本)

      那么您提供的代码将在 html5 画布中工作(没有错误)。

      由于您使用的是 pdf.js,因此您的错误可能出现在您没有向我们展示的代码中。

      确保您为 pdf.js 提供了一个有效的上下文

      此提醒应为CanvasRenderingContext2D

      // test if the context you're feeding pdf.js is valid
      
      alert(ctx);
      
      // feed pdf.js the context
      
      var myPDFContext = {
        canvasContext: ctx,
        viewport: viewport
      };
      page.render(myPDFContext);
      

      【讨论】:

        【解决方案6】:

        如果最近偶然发现它,请补上。

        // Canvas class to contain info about element and canvas
        // and convenient API for drawing
        var Canvas = function (id) {
            this.element = document.getElementById('my-canvas');
        
            // if canvas element doesn't exist...
            if (!this.element) {
                throw new Exception('Canvas $id not found.'.replace('$id', id));
            }
        
            // if the getContext method doesn't exist (old browser)
            if (!this.element.getContext) {
                throw new Exception('Canvas $id cannot load contexts.'.replace('$id', id));
            }
        
            this.context2d = this.element.getContext('2d');
        
            // if this particular context isn't supported
            if (!this.context2d) {
                throw new Exception('Canvas $id cannot load 2D context.'.replace('$id', id));
            }
        };
        
        // draw a line through each of the given points
        Canvas.prototype.drawLine = function (points) {
            for (var i = 0, l = points.length; i < l; i++) {
                var point = points[i];
        
                // if it's the first point, start a path
                // otherwise, continue from the previous point
                if (i === 0) {
                    this.context2d.beginPath();
                    this.context2d.moveTo(point[0], point[1]);
                } else {
                    this.context2d.lineTo(point[0], point[1]);
                }
            }
            this.context2d.stroke();
        };
        
        // create a reference point for our Canvas instance
        var myCanvas;
        
        // initialize our Canvas instance on page load
        function initCanvas() {
            try {
                myCanvas = new Canvas('my-canvas');
        
                // draw a diagonal line from the top left to the bottom right
                // use actual width and height, not CSS properties,
                // unless you want blurred content
                myCanvas.drawLine([
                    [0, 0],
                    [myCanvas.element.width, myCanvas.element.height]
                ]);
            }
            catch(exc) {
                window.alert(exc);
            }
        }
        
        document.addEventListener('DOMContentLoaded', initCanvas, false);
        

        【讨论】:

        • 没有错...我怀疑 OP 在他的代码中的其他地方有问题。 +1 扭转别人的缺点。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 2016-06-26
        • 2023-03-05
        • 2021-08-14
        相关资源
        最近更新 更多