1

I am using Vue and need the files to preview before upload, if file is image then reduce its size (using canvas) and display, else just display the extension of file using canvas, so I have done something like this:

// I have used this function in the html like <img src={{ imagePreviewURL(File) }} />
imagePreviewURL(File) { // <-- get the uploaded file
  const canvas = document.createElement('canvas')!; // <-- create canvas
  const ctx = canvas.getContext('2d')!;
  canvas.width = 100;
  canvas.height = 100;
  if (File.type.includes('image')) { // <-- if file is image
    const image = new Image(); // <-- create new image
    image.onload = () => {
      ctx.drawImage(image, 100, 100); // <-- draw image to canvas
    };
    image.src = URL.createObjectURL(File); // <-- set source of image
  } else {
    ctx.font = '30px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(`.${File.name.split('.').pop()!}`, 50, 55); // <-- just display extension
  }
  return ctx.canvas.toDataURL(); // <-- convert canvas to image
}

The extension part works very fine, but the image is not showing.

6
  • image.onload is async it isn't going to run before you return ctx.canvas.toDataURL() therefore your image isn't drawn to the canvas before the function returns. Commented Nov 16, 2019 at 6:15
  • Can you give the solution to this? Commented Nov 16, 2019 at 6:16
  • How to async await it? Commented Nov 16, 2019 at 6:19
  • Instated of file send the event and call like -: This method is prefixed in Chrome and Webkit as window.webkitURL.createObjectURL(). You should test if URL exists and then use the appropriate object: (window.URL ? URL : webkitURL).createObjectURL(evt.data); Commented Nov 16, 2019 at 7:24
  • @LDS already done this. Commented Nov 16, 2019 at 8:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.