gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'getContext' of null at zoom. html:8

转载 作者:行者123 更新时间:2023-11-28 04:02:32 25 4
gpt4 key购买 nike

我正在尝试创建一个图像缩放,如果您将鼠标悬停在图像上,让它在定义的宽度上缩放图像。沿着这条线我得到了

Uncaught TypeError: Cannot read property 'getContext' of null
at zoom.html:8

在我的 html 文件中。这是我遇到挑战的 html 文件的片段

var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
iw, ih;

在 html 文件的正文中我有这个片段

<canvas width="310" height="305" id="canvas">Sorry, no canvas available</canvas>
<a id="download" download="download.jpg">Download as image</a>

这是我做的一个plunk demo

http://plnkr.co/edit/0G93qmVeUWby0SRIp5Br

请问哪里出了问题?

最佳答案

您正在尝试在 DOM 加载之前访问 DOM 中的元素。比较这两个例子:

<script>
console.log(document.getElementById('canvas'));
</script>
<canvas id="canvas"></canvas>

<canvas id="canvas"></canvas>
<script>
console.log(document.getElementById('canvas'));
</script>

正如您可能已经注意到的,解决方案是在页面加载后运行您的脚本,即在 <body> 的底部.

关于javascript - 未捕获的类型错误 : Cannot read property 'getContext' of null at zoom. html:8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43125714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com