无法获取未定义或空引用的属性“addEventListener”

时间:2014-06-18 15:11:49

标签: javascript canvas addeventlistener

我需要在canvas标签上放置一个图像,并且总是给我这个错误:

“无法获取未定义或空引用的属性'addEventListener'”

请帮助我谢谢

CODE:

HTML:

<div id="page">
    <h2>Template Editor</h2>
    <div id="input">

        <form>
            <p>Select a file: <input type='file' id="inputFile" name="inputFile" /></p>
            <p>Load source file (*.bmp, *.jpg, *.tif, *.pdf)</p>
        </form>
    </div>
    <div id="menu">
        <ul>
            <li><button><span>OCR</span></button></li>
            <li><button><span>ICR</span></button></li>
            <li><button><span>OMR</span></button></li>
        </ul>
    </div>

    <div id="canvasObj">
        <canvas id="myCanvas">
            Your browser does not support the HTML5 canvas tag.
        </canvas>

    </div>
</div>

使用Javascript:

var imageLoader = document.getElementById('inputFile');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');


function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
        var img = new Image();
        img.onload = function () {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);
}

2 个答案:

答案 0 :(得分:0)

尝试像这样包装你的JS:

window.addEventListener("load", function() {
    var imageLoader = document.getElementById('inputFile');
    imageLoader.addEventListener('change', handleImage, false);
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');


    function handleImage(e) {
        var reader = new FileReader();
        reader.onload = function (event) {
            var img = new Image();
            img.onload = function () {
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0);
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);
    }
});

解释:DOM在JS之后加载,因此无法定义。

答案 1 :(得分:-1)

这些有助于解决我的问题:

  • <body>末尾移动脚本参考
  • 确保使用document.getElementByID调用Element ID时没有错字