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元素。
想法?
答案 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');
还有更多错误。这是一个有效的代码,但在我看来,即使它有效也很混乱。