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.

U-Dev
  • 517
  • 2
  • 14
  • `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. – Patrick Evans Nov 16 '19 at 06:15
  • Can you give the solution to this? – U-Dev Nov 16 '19 at 06:16
  • How to async await it? – U-Dev Nov 16 '19 at 06: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); – LDS Nov 16 '19 at 07:24
  • @LDS already done this. – U-Dev Nov 16 '19 at 08:14
  • `function imagePreviewURL(file) { return new Promise( (resolve, reject) => { const canvas = /*[...]*/ if(file.type.includes('image')) { const image= new Image(); image.onload = () => { ctx.drawImage(image, 100, 100); canvas.toBlob((blob) => resolve(URL.createObjectURL(blob))); }; image.src = URL.createObjectURL(file); } else { ctx.font = '30px Arial'; ctx.textAlign = 'center'; ctx.fillText(\`.${file.name.split('.').pop()}\`, 50, 55); ctx.toBlob( (blob) => resolve(URL.createObjectURL(blob))); } }` – Kaiido Nov 16 '19 at 09:04

0 Answers0