[英]Uncaught TypeError: Cannot read property 'getContext' of null at zoom.html:8
I am trying to create an image zoom where by if you hover over the mouse over the image let it zoom the image on the defined width. 我正在尝试创建图像缩放,如果您将鼠标悬停在图像上,则将其缩放到定义的宽度。 Along the line I am getting
沿线我越来越
Uncaught TypeError: Cannot read property 'getContext' of null
at zoom.html:8
in my html file. 在我的html文件中。 This is a snippet of the html file I am having the challenge with
这是我遇到的html文件的摘要
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
iw, ih;
In the body of the html file I have this snippet 在html文件的主体中,我有以下代码段
<canvas width="310" height="305" id="canvas">Sorry, no canvas available</canvas>
<a id="download" download="download.jpg">Download as image</a>
here is a plunk demo I have made 这是我制作的一个小样的演示
http://plnkr.co/edit/0G93qmVeUWby0SRIp5Br
Please what could be wrong? 请问可能有什么问题吗?
You're attempting to access an element in the DOM before it's loaded. 您正在尝试在DOM中加载元素之前对其进行访问。 Compare these two examples:
比较这两个示例:
<script> console.log(document.getElementById('canvas')); </script> <canvas id="canvas"></canvas>
<canvas id="canvas"></canvas> <script> console.log(document.getElementById('canvas')); </script>
As you may have picked up, the solution is to run your script after the page is loaded, ie at the bottom of the <body>
. 您可能已经接过,解决方案是在页面加载后即
<body>
的底部运行脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.