调整画布大小可动态生成空白画布

时间:2018-07-06 08:46:47

标签: javascript canvas

我正在尝试根据要绘制的图像数量动态调整画布的大小。

仅适用于一张图像。如果我有多个图像,则画布为空白。

this.imageWidth给出了第一张图片的宽度),this.heightCanvas给出了所有图片的总高度。

因为我想将所有图像放置在垂直行中。

HTML

<div id="canvasWrapper"></div>

JS

  startCanvas() {
  var canvasExists = document.getElementById('ocrCanvas');

  if (canvasExists != null) {
    alert(canvasExists);
    var myNode = document.getElementById("canvasWrapper");
    while (myNode.firstChild) {
        myNode.removeChild(myNode.firstChild);
    }
  }
  var canv = document.createElement('canvas');
  canv.id = 'ocrCanvas';
  document.getElementById('canvasWrapper').appendChild(canv); // adds the canvas to #someBox

  const getContext = () => document.getElementById('ocrCanvas').getContext('2d');
  const ctx = getContext();
  ctx.canvas.width  = this.imageWidth;
  ctx.canvas.height = this.heightCanvas;

  console.log('ctx width' + ctx.canvas.width)
  console.log('ctx height' + ctx.canvas.height)

  this.fillCanvas();

}

fillCanvas() {
const getContext = () => document.getElementById('ocrCanvas').getContext('2d');

const loadImage = url => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error(`load ${url} fail`));
    img.src = url;
  });
};

const depict = options => {
  const ctx = getContext();
  ctx.canvas.width  = this.imageWidth;
  ctx.canvas.height = this.heightCanvas;

  console.log('ctx width' + ctx.canvas.width)
  console.log('ctx height' + ctx.canvas.height)

  const myOptions = Object.assign({}, options);
  return loadImage(myOptions.src).then(img => {

    ctx.drawImage(img, myOptions.x, myOptions.y);
  });
};

const imgs = this.base64Canvas;
imgs.forEach(depict);
};

0 个答案:

没有答案