图像串联脚本

时间:2019-05-30 09:28:53

标签: javascript html canvas

每个人。我正在尝试编写一个脚本,以连续从画布上的文件输入中呈现图像。

首先,我循环浏览图像以计算画布宽度(因为在调整大小时会擦除画布)。然后再次循环以渲染图像。

canvas.width = 0;
let x = 0,
    y = 0,
    totalWidth = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.files[0];
  let img = new Image();
  console.log(img);
  img.src = window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    console.log(img);
    let newWidth = img.width * canvas.height / img.height;
    totalWidth += newWidth;
    canvas.width = totalWidth;
  }, false);
};
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.files[0];
  let img = new Image();
  img.src = window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    let newWidth = img.width * canvas.height / img.height;
    ctx.drawImage(img, x, y, newWidth, canvas.height);
    x += newWidth;
  }, false);
};

}

该应用程序的行为很怪异,图像并非总是呈现,而当它们呈现时,并不总是呈现在预期的位置。

1 个答案:

答案 0 :(得分:1)

代码的第一个问题是您要加载两次图像,而随机性是由于图像加载可能不明确所致。看看这个jsfiddle。我使用文本输入而不是文件输入,绘制是在最后一张图像时进行的,否则调整画布的大小可能会导致画布重置,从而丢失上一个绘制。

var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d', {
		antialias: false,
		depth: false
	});
canvas.width = 0;
let x = 0,
    y = 0,
    totalWidth = 0;
    let obj = [];
    let k = 0;
for (let i = 0; i < document.querySelectorAll(".has-file").length; i++) {
  let input = document.querySelectorAll(".has-file")[i];
  let image = input.value;
  let img = new Image();
  img.src = image;//window.URL.createObjectURL(image);
  img.addEventListener('load', () => {
    console.log(img);
    let newWidth = img.width * canvas.height / img.height;
    totalWidth += newWidth;
    canvas.width = totalWidth;
    obj.push({img: img, x: x, y: y, newWidth: newWidth, height: canvas.height});
    k++;
    x += newWidth;
    if (k == document.querySelectorAll(".has-file").length )
    	draw();
  }, false);
};

function draw() {
  for (var i = 0; i < obj.length; i++) {
      ctx.drawImage(obj[i].img, obj[i].x, obj[i].y, obj[i].newWidth, obj[i].height);
  }
}
<input style="display: none;" class="has-file" value="https://i.imgur.com/I86rTVl.jpg" />
<input style="display: none;" class="has-file" value="https://images.unsplash.com/photo-1446292267125-fecb4ecbf1a5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80" />

<canvas id="canvas"></canvas>