Skip to content

Instantly share code, notes, and snippets.

@alastaircoote
Last active December 6, 2016 14:38
Show Gist options
  • Save alastaircoote/8330ba369ff37965e072ebca21a9896f to your computer and use it in GitHub Desktop.
Save alastaircoote/8330ba369ff37965e072ebca21a9896f to your computer and use it in GitHub Desktop.
import opentype from 'opentype.js';
let lastRenderTime = null;
let x = 0;
let y = 0;
let moveBackwards = false;
let moveUp = false;
let logoImg = null;
let parsedFont = null;
let renderTimes = [];
const doRender = function(e) {
let ctx = e.canvas.getContext('2d');
ctx.clearRect(Math.floor(x), Math.floor(y), logoImg.width, logoImg.height)
let now = Date.now();
if (lastRenderTime) {
let diff = now - lastRenderTime;
if (moveBackwards) {
x -= (diff / 1000) * 500
} else {
x += (diff / 1000) * 500
}
if (moveUp) {
y -= (diff / 1000) * 500
} else {
y += (diff / 1000) * 500
}
if (x > e.canvas.width - logoImg.width) {
x = e.canvas.width - logoImg.width;
moveBackwards = true;
} else if (x <= 0) {
moveBackwards = false;
x = 0;
}
if (y > e.canvas.height - logoImg.height) {
moveUp = true;
} else if (y <= 0) {
moveUp = false;
}
}
lastRenderTime = now;
ctx.font = "30px Helvetica"
ctx.fillColor = "#000000";
ctx.clearRect(0,0,200,50);
ctx.drawImage(logoImg, Math.floor(x), Math.floor(y));
renderTimes.push(Date.now())
if (renderTimes.length > 200) {
renderTimes.shift();
}
let framesInLastSecond = renderTimes.filter((r) => r > Date.now() - 1000).length
var path = parsedFont.getPath(framesInLastSecond + 'fps', 0, 30, 30);
path.draw(ctx);
e.requestAnimationFrame();
}
self.addEventListener('notificationcanvasshow', function(e) {
x = 0;
y = 0;
lastRenderTime = null;
moveUp = false;
moveBackwards = false;
e.waitUntil(
caches.open('v1')
.then((cache) => {
return Promise.all([
cache.match('images/brexit_result_test.png')
.then((res) => res.blob())
.then((blob) => createImageBitmap(blob))
.then((imgBitmap) => {
logoImg = imgBitmap;
return logoImg
})
,
cache.match('gdn.otf')
.then((res) => {
return res.arrayBuffer()
})
.then((buffer) => {
parsedFont = opentype.parse(buffer)
})
])
})
.then(() => {
doRender(e);
})
)
})
self.addEventListener("notificationcanvasframe", doRender);
// Can be invoked by:
self.registration.showNotification({
title: 'A Canvas Notification',
options: {
body: "This is a canvas notification",
hideText: true,
canvas: {
proportion: 0.7
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment