从输入动态添加多个图像

时间:2015-07-06 12:23:01

标签: javascript canvas

我有以下代码:

      var imageLoader = document.getElementById('imageLoader');
    var patternLoader = document.getElementById("patternLoader");
    var canvas = document.getElementById('imageCanvas');
    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]);
    };

    imageLoader.addEventListener("change", handleImage, false);
    patternLoader.addEventListener("change", handleImage, false);

如何从输入加载一个图像而不是替换它们?

我希望它像那样http://i.gyazo.com/85c8c6bdcd2efcdd6a1c1b156000f204.png

1 个答案:

答案 0 :(得分:0)

这是一种动态添加图像的粗略方法。声明一个数组以跟踪所有图像并根据最大图像缩放画布。

因为我没有知道OP用于什么样的DOM元素&#34; imageLoader&#34;和&#34; patternLoader&#34;,我只是使用<input> - 标记。

只需粘贴图片网址即可将图片添加到画布中。在添加图像时,图像将按顺序绘制。

&#13;
&#13;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var maxWidth = 0;
var maxHeight = 0;
var images = [];

var myInput = document.getElementById("myInput");
myInput.addEventListener('change',handleImage,false);

function handleImage(e) {
    var myImage = new Image();
    myImage.onload = function () {   
        if (myImage.width > maxWidth) {
            maxWidth = myImage.width;
        }
        if (myImage.height > maxHeight) {
            maxHeight = myImage.height;
        }
        canvas.width = maxWidth;
        canvas.height = maxHeight;
        images.push(myImage);
        drawImages();
    }
    myImage.src = e.target.value;
}

function drawImages() {
    for (var i = 0; i<images.length; i++) {
        ctx.drawImage(images[i],canvas.width/2-images[i].width/2,canvas.height/2-images[i].height/2);
    }
}
&#13;
<input type="text" id="myInput"><br />
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;