Home > front end >  How do you draw an image from data URL to a HTML canvas?
How do you draw an image from data URL to a HTML canvas?

Time:09-07

I am trying to draw images from a data URL (obtained from user-provided files) onto a canvas using the Canvas API and then using JsZip to package the resulting images in a zip file which is to be downloaded.

Note: The canvas is never actually displayed to the user. It only serves as a framebuffer.

The problem is the image is not drawn onto the canvas when using the 'drawImage' function in the following way (from a different solution):

const url = URL.createObjectURL(acceptedFiles[image])
const img = new Image()
img.onload = () => ctx.drawImage(img, column, row, imageWidth, imageHeight)
img.src = url

I'm not sure why onl oad is being used here but it seems quite counterintuitive to me as the canvas in not supposed to be seen by the user. Other functions like 'fillRect' work fine it's only 'drawImage' that is not working for me.

I'm not sure if and how I would use a different CanvasImageSource but this code results in nothing but a blank screen.

Another issue is with how the resulting image is archived.

I am using JsZip to archive the resulting image but that also doesn't work and I am left with an empty zip file. Here is the code that does that:

const filename = `Page ${i   1}.png`
const data = canvas.toDataURL()
zip.file(filename, data)

CodePudding user response:

The image was not drawing because I wasn't awaiting the loading of the image. Awaiting this function solved my problem:

const loadImage = (url: string) => {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    const img = new Image()
    img.onload = () => {
      resolve(img)
    }

    img.onerror = reject

    img.src = url
  })
}

After, I used 'then' to draw the image once it has been loaded:

await loadImage(url).then((imageSource) =>
  ctx.drawImage(
    imageSource,
    column * imageWidth,
    row * imageHeight,
    imageWidth,
    imageHeight
  )
)

CodePudding user response:

Umarım çözülür kral

    await loadImage(url).then((imageSource) =>
  ctx.drawImage(
    imageSource,
    column * imageWidth,
    row * imageHeight,
    imageWidth,
    imageHeight
  )

bunu dene

  • Related