简体   繁体   中英

How do you draw an image from data URL to a HTML canvas?

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 onload 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)

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
  )
)

Umarım çözülür kral

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

bunu dene

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM