Vinny
Vinny

Reputation: 63

Can I combine a canvas and an image element in javascript?

I want to convert my "image" variable to a canvas type and combine it with "canvas" variable(boxes) element to create another canvas element. This output canvas would have the image behind and the canvas with boxes on the front. I am referring to http://jsfiddle.net/bnwpS/878/

HTML:

<div id="output"></div>

Javascript:

const container = document.getElementById("output");
const image = await faceapi.bufferToImage(imageUpload.files[0]);
const canvas = faceapi.createCanvasFromMedia(image);
container.append(image);
container.append(canvas);

I have tried one thing but was unsuccessful:

  1. created another canvas element using createElement('canvas') and then using drawImage() to draw the image and the canvas on it, however the result comes out as black.

Upvotes: 0

Views: 632

Answers (2)

OlegSuncrown
OlegSuncrown

Reputation: 21

img1.onload = () => {
  canvas.width = img1.width;
  canvas.height = img1.height;
  img2.src = 'img2.png';
};

img2.onload = () => {
  context.drawImage(img1, 0, 0);
  context.drawImage(img2, 0, 0);

  const imgUrl = canvas.toDataURL('image/jpeg');
  this.selectedImg = imgUrl;
  // convert canvas to file format
  canvas.toBlob((blob: any) => {
    let file = new File([blob], image.name, { type: 'image/jpeg' });
    console.log(file);
  }, 'image/jpeg');
};
img1.src = 'img1.png';

Taken from https://youtu.be/th8l_l_WA3k

Upvotes: 0

see sharper
see sharper

Reputation: 12025

Try writing the image to the canvas using this function:

function writeImageToCanvas(image, cvs) {
  const img = document.createElement('img');
  return new Promise(resolve => {
    img.onload = () => {
      cvs.width = img.width;
      cvs.height = img.height;
      const ctx = cvs.getContext('2d');
      ctx.drawImage(img, 0, 0);
      resolve();
    };
    img.src = image.src;
  });
}

Note this is an async function, so will need to use writeImageToCanvas(img,cvs).then(... or else use await and mark the calling function as async.

Upvotes: 2

Related Questions