Automattic / node-canvas

Node canvas is a Cairo backed Canvas implementation for NodeJS.
10.2k stars 1.17k forks source link

Support `ImageBitmap` and `createImageBitmap` #876

Open brettz9 opened 7 years ago

brettz9 commented 7 years ago

Feature

Add and expose ImageBitmap and createImageBitmap and allow their use within relevant canvas methods (ideally also working with jsdom to hook into this as well).

piranna commented 5 years ago

Does this include to define it as a context?

brettz9 commented 5 years ago

That would need to be done on the end of jsdom (or whatever DOM library), but yes, the request is for allowing node-canvas to be used by such libraries for such purposes.

jimmywarting commented 1 year ago

NodeJS just introduced a fs.openAsBlob()

import { openAsBlob } from 'node:fs'
const blob = await openAsBlob('the.file.png')
const bitmap = await createImageBitmap(blob)

you may also fetch blobs natively

const blob = await response.blob()
liudonghua123 commented 1 year ago

I want to make https://github.com/imgly/background-removal-js support both web and node platform, and I found this canvas for node project but it seems missing some api like createImageBitmap and so on, how can I implements in node?

See also:

jimmywarting commented 1 year ago

If you would like to support some basic version of createImageBitmap yourself right now you could implement something like:

import { openAsBlob } from 'node:fs'
import { Image } from 'canvas'

async function createImageBitmap (blob) {
  const ab = await blob.arrayBuffer()
  const img = new Image()
  await new Promise(rs => {
    img.onload = rs
    img.src = new Uint8Array(ab) // might have to do: Buffer.from(ab)
  })
  return img
}

const blob = await fetch(request).then(res => res.blob())
const blob = await openAsBlob('the.file.png')
const bitmap = await createImageBitmap(blob)

imo i think that the Image class should be removed / deprecated and be replaced with a own built in createImageBitmap powered by node-canvas

cayblood commented 1 year ago

@jimmywarting the code sample above refers to undefined methods, like squid, and the ab arrayBuffer never gets used. Can you please fix that code snippet for those of us who aren't as familiar?

jimmywarting commented 1 year ago

@cayblood ups, updated - thanks