无法读取null的属性“ getContext” [英] Cannot read property 'getContext' of null

查看:429
本文介绍了无法读取null的属性“ getContext”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,单击该按钮即可执行此功能。此代码是在画布元素上画一条线,并使用PDF.JS在PDF元素呈现在网页上。但是我收到一个错误未捕获的TypeError:无法读取null的属性 getContext。我应该怎么办。

I have a button which on click executes this function.This code is to draw a line on canvas element on which PDF file gets rendered on a webpage by using PDF.JS. But i get an error "Uncaught TypeError: Cannot read property 'getContext' of null". What should i do.

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


推荐答案

首先,您应检查null:

Firstly, you should check for null:

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

第二,确保您具有元素 canvas1 -如果存在,则 c 不应为 null ;如果不存在,则代码和内容之间会有差异,并且您需要确定在这种情况下应发生的情况,如果应该从不发生,那么这是例外,也许您想要错误,将被引发,或您自己指定的消息,或其他内容。

Secondly, make sure you have an element canvas1 - if it exists then c should not be null; if it doesn't exist then there's a discrepancy between the code and content, and you need to decide what should happen in circumstances when this occurs, if it should never occur then it's exceptional and maybe you want the error the be raised, or a message of your own specified, or something.

这篇关于无法读取null的属性“ getContext”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆