W3C home > Mailing lists > Public > whatwg@whatwg.org > March 2015

[whatwg] Canvas image to blob/dataurl within Worker

From: Jake Archibald <jaffathecake@gmail.com>
Date: Fri, 20 Mar 2015 12:13:31 +0000
Message-ID: <CAJ5xic96qh-apexqtyYsUsnk29FwhgwYjzapOcwvuGdR8oyvrA@mail.gmail.com>
To: WHATWG <whatwg@whatwg.org>
Usecase:

Receiving a push message results in a 'push' event within the
ServiceWorker. The likely action at this point is to show a notification.
It should be possible to generate an image to use as an icon for this
notification (
https://notifications.spec.whatwg.org/#dom-notificationoptions-icon).

This could be a badge showing some kind of unread count, some combination
of app icon & avatar, or even a default avatar (Google Inbox generates an
avatar from the senders names first letter).

This is also useful for generating images to go into the cache API, or
transforming images as they pass through the ServiceWorker.

API:

Almost all the pieces already exist, except a way to get the image data of
a CanvasRenderingContext2D into a format that can be read from a
url. ImageBitmap seems like a good fit for such an API:

var context = new CanvasRenderingContext2D(192, 192);

Promise.all(
  caches.match('/avatars/ben.png')
    .then(r => r.blob())
    .then(b => createImageBitmap(b)),
  caches.match('/avatars/julie.png')
    .then(r => r.blob())
    .then(b => createImageBitmap(b)),
).then(([ben, julie]) => {
  context.drawImage(ben, 0, 0);
  context.drawImage(julie, 96, 96);
  return createImageBitmap(context);
}).then(
  // **** and here's the bit we're missing… ****
  image => image.toDataURL()
).then(icon => {
  self.registration.showNotificaiton("Hello!", {icon});
});
Received on Friday, 20 March 2015 12:13:58 UTC

This archive was generated by hypermail 2.4.0 : Wednesday, 22 January 2020 17:00:29 UTC