Javascript 无法读取属性';getContext';空的

Javascript 无法读取属性';getContext';空的,javascript,canvas,pdf.js,Javascript,Canvas,Pdf.js,我有一个按钮,点击执行这个功能。这段代码是在画布元素上画一条线,在这个元素上使用PDF.JS呈现PDF文件。但我得到一个错误“UncaughtTypeError:无法读取null的属性'getContext'。我该怎么办 function abc() { alert("msg"); var c=document.getElementById("canvas1"); alert(c); var ctx= c.getContext('2d'); alert(ctx); ctx.beginPath()

我有一个按钮,点击执行这个功能。这段代码是在画布元素上画一条线,在这个元素上使用PDF.JS呈现PDF文件。但我得到一个错误“UncaughtTypeError:无法读取null的属性'getContext'。我该怎么办

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();
}

首先,您应该检查空值:

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

其次,确保您有一个元素
canvas1
——如果它存在,则
c
不应为
null
;如果它不存在,那么代码和内容之间就存在差异,您需要决定在出现这种情况时应该发生什么,如果它永远不会发生,那么它就是例外,可能您希望引发错误,或者您自己指定的消息,或者其他什么。

您的代码在我看来是有效的(刚刚添加了以下HTML):

按钮

如果最近偶然发现,则会进行润色

// 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);
//Canvas类包含有关元素和画布的信息
//以及方便的绘图API
var Canvas=函数(id){
this.element=document.getElementById('my-canvas');
//如果画布元素不存在。。。
if(!this.element){
抛出新异常('Canvas$id not found.'.replace('$id',id));
}
//如果getContext方法不存在(旧浏览器)
如果(!this.element.getContext){
抛出新异常('Canvas$id无法加载上下文。'.replace('$id',id));
}
this.context2d=this.element.getContext('2d');
//如果不支持此特定上下文
如果(!this.context2d){
抛出新异常('Canvas$id无法加载2D上下文。'.replace('$id',id));
}
};
//通过每个给定点画一条线
Canvas.prototype.drawLine=函数(点){
对于(变量i=0,l=points.length;i
假设您的警报报告中有对画布和上下文的有效引用:

警报#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);

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

检查脚本的位置。我已经将它包含在
部分,很明显,它试图nd
canvas
元素,甚至在将其附加到DOM之前。因此会出现
undefined
null
错误。

是否有ID为
canvas1
的元素?该错误强烈建议您不要这样做!如果canvas1是在使用pdf.js的itIm的脚本标记下面定义的,则也会出现相同的错误在我的网站上呈现pdf文件。我无法访问在其上呈现pdf文件的画布。此代码是程序的一部分。我已尝试过您的解决方案,显然“c”为空。如果您了解pdf.js,请帮助我。感谢您的帮助。如果
c
null
则您没有id为
id的画布=“canvas1”
。将其更改为画布的ID。没有问题……我怀疑OP在其代码中的其他地方有问题。+1可反转其他人的缺点。
// 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);