为什么我的javascript无法上传图片并将其放在带有此代码的canvas元素中?

时间:2014-01-17 22:17:15

标签: javascript html5 image canvas upload

function addMoreFileUploads(id){
    var canvasName =  'canvas' + id;
    var canvas = document.getElementById(canvasName);



    $("#fileUploads").append('<input id="' + id + '" type="file" name="files[]" /> <br><br>');

    $("#canvasInsert").append('<canvas id="'+ canvasName +'" style="border:1px solid #000000;" width="500" height="500"></canvas>');

    var imageLoader = document.getElementById(id); //OnChange="upl()" 

    imageLoader.addEventListener('change',
        function(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]);   
        },false);
}

尝试使它成为当我添加一个输入元素时,它还附加一个事件监听器,它会查找一个图像,然后将其读入已经创建的canvas元素。

想法?

1 个答案:

答案 0 :(得分:2)

var canvas = document.getElementById(canvasName);

将为null,因为在您的DOM中此时没有canvas元素

function addMoreFileUploads(id){

    var canvasName =  'canvas' + id;

    $("#fileUploads").append('<input id="' + id + '" type="file" name="files[]" /> <br><br>');
    $("#canvasInsert").append('<canvas id="'+ canvasName +'" style="border:1px solid #000000;" width="500" height="500"></canvas>');

    var canvas = document.getElementById(canvasName),
        ctx = canvas.getContext("2d");

    var imageLoader = document.getElementById(id); //OnChange="upl()" 

    imageLoader.addEventListener('change',
        function(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]);   
        },false);
}

addMoreFileUploads('foo');

还有更多错误。这是一个有效的代码,但在我看来,即使它有效也很混乱。

演示: http://jsfiddle.net/LqjLD/1/