Skip to content
This repository has been archived by the owner on Jan 16, 2024. It is now read-only.

Commit

Permalink
Add examples for OffscreenCanvas and Web Workers (#158)
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperSodaSea authored Nov 8, 2022
1 parent d7e2dd7 commit 4f42ecd
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 14 deletions.
38 changes: 38 additions & 0 deletions public/examples/js/offscreen-canvas/basic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// This example is the based on demos-basic/container, but using OffscreenCanvas.

const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const view = canvas.transferControlToOffscreen();

const app = new PIXI.Application({ view, background: 0x1099bb });

const container = new PIXI.Container();

app.stage.addChild(container);

// Create a new texture
const texture = PIXI.Texture.from('examples/assets/bunny.png');

// Create a 5x5 grid of bunnies
for (let i = 0; i < 25; i++) {
const bunny = new PIXI.Sprite(texture);
bunny.anchor.set(0.5);
bunny.x = (i % 5) * 40;
bunny.y = Math.floor(i / 5) * 40;
container.addChild(bunny);
}

// Move container to the center
container.x = app.screen.width / 2;
container.y = app.screen.height / 2;

// Center bunny sprite in local container coordinates
container.pivot.x = container.width / 2;
container.pivot.y = container.height / 2;

// Listen for animate update
app.ticker.add((delta) => {
// rotate the container!
// use delta to create frame-independent transform
container.rotation -= 0.01 * delta;
});
66 changes: 66 additions & 0 deletions public/examples/js/offscreen-canvas/web-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// This example is the based on demos-basic/container, but running in Web Worker.

function workerSource(self) {
self.onmessage = async ({
data: { baseUrl, pixiWebWorkerUrl, options },
}) => {
self.importScripts(new URL(pixiWebWorkerUrl, baseUrl));

const app = new PIXI.Application(options);

const container = new PIXI.Container();

app.stage.addChild(container);

// Create a new texture
const textureUrl = new URL('examples/assets/bunny.png', baseUrl).toString();
const texture = PIXI.Texture.from(textureUrl);

// Create a 5x5 grid of bunnies
for (let i = 0; i < 25; i++) {
const bunny = new PIXI.Sprite(texture);
bunny.anchor.set(0.5);
bunny.x = (i % 5) * 40;
bunny.y = Math.floor(i / 5) * 40;
container.addChild(bunny);
}

// Move container to the center
container.x = app.screen.width / 2;
container.y = app.screen.height / 2;

// Center bunny sprite in local container coordinates
container.pivot.x = container.width / 2;
container.pivot.y = container.height / 2;

// Listen for animate update
app.ticker.add((delta) => {
// rotate the container!
// use delta to create frame-independent transform
container.rotation -= 0.01 * delta;
});
};
}
const blob = new Blob(['(', workerSource, ')(self);'], { type: 'application/javascript' });
const url = URL.createObjectURL(blob);
const worker = new Worker(url);
URL.revokeObjectURL(url);

const width = 800;
const height = 600;
const resolution = window.devicePixelRatio;
const canvas = document.createElement('canvas');
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
document.body.appendChild(canvas);
const view = canvas.transferControlToOffscreen();

const baseUrl = window.location.href;
const pixiWebWorkerUrl = window.PIXI_WEBWORKER_URL;
worker.postMessage({
baseUrl,
pixiWebWorkerUrl,
options: {
width, height, resolution, view, background: 0x1099bb,
},
}, [view]);
17 changes: 16 additions & 1 deletion public/examples/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,21 @@
]
},
{
"id": "offscreen-canvas",
"title": "Offscreen Canvas",
"items": [{
"title": "Basic",
"entry": "basic.js",
"features": ["OffscreenCanvas"]
},
{
"title": "Web Worker",
"entry": "web-worker.js",
"features": ["OffscreenCanvas"]
}
]
},
{
"id": "filters-basic",
"title": "Filters - Basic",
"items": [{
Expand Down Expand Up @@ -789,4 +804,4 @@
]
}]
}
]
]
50 changes: 37 additions & 13 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ jQuery(document).ready(($) => {
bpc.autoPlay = true;
bpc.packagesManifest = {};

bpc.browserFeatures = {
OffscreenCanvas: typeof OffscreenCanvas === 'function',
};

bpc.init = function init() {
const embedded = bpc.embedMode();

Expand All @@ -71,7 +75,8 @@ jQuery(document).ready(($) => {
items.filter((item) => item.visible !== false).forEach((item) => {
const plugins = typeof item.plugins !== 'undefined' ? item.plugins.join(',') : '';
const validVersions = typeof item.validVersions !== 'undefined' ? item.validVersions.join(',') : '';
html += `<li data-src="${item.entry}" data-plugins="${plugins}" data-validVersions="${validVersions}">${item.title}</li>`;
const features = typeof item.features !== 'undefined' ? item.features.join(',') : '';
html += `<li data-src="${item.entry}" data-plugins="${plugins}" data-validVersions="${validVersions}" data-features="${features}">${item.title}</li>`;
});
html += '</ul>';
$('.main-menu').append(html);
Expand Down Expand Up @@ -190,6 +195,9 @@ jQuery(document).ready(($) => {
const validVersions = $(this).attr('data-validVersions');
bpc.exampleValidVersions = validVersions === '' ? [7] : validVersions.split(',').map((v) => parseInt(v, 10));

const features = $(this).attr('data-features');
bpc.exampleFeatures = features === '' ? [] : features.split(',');

$.ajax({
url: `examples/js/${$(this).parent().attr('data-section')}/${$(this).attr('data-src')}`,
dataType: 'text',
Expand Down Expand Up @@ -223,11 +231,14 @@ jQuery(document).ready(($) => {

// Generate HTML and insert into iFrame
let pixiUrl = '';
let pixiWebWorkerUrl = '';

if (bpc.pixiVersionString === 'local') {
pixiUrl = 'dist/pixi.js';
pixiWebWorkerUrl = 'dist/webworker.js';
} else { // other versions come from S3
pixiUrl = `https://d157l7jdn8e5sf.cloudfront.net/${bpc.pixiVersionString}/pixi-legacy.js`;
pixiWebWorkerUrl = `https://d157l7jdn8e5sf.cloudfront.net/${bpc.pixiVersionString}/webworker.js`;
}

let html = '<!DOCTYPE html><html><head><style>';
Expand Down Expand Up @@ -259,6 +270,8 @@ jQuery(document).ready(($) => {
}
}

bpc.missingFeatures = bpc.exampleFeatures.filter((x) => !bpc.browserFeatures[x]);

bpc.editor = CodeMirror.fromTextArea(document.getElementById('code'), bpc.editorOptions);

if (bpc.exampleRequiredPlugins.length) {
Expand All @@ -267,24 +280,35 @@ jQuery(document).ready(($) => {
$('#code-header').text('Example Code');
}

if (!bpc.exampleValidVersions.length || bpc.exampleValidVersions.indexOf(bpc.majorPixiVersion) > -1) {
$('#example-title').html(bpc.exampleTitle);
html += `<script>window.onload = function(){${bpc.exampleSourceCode}}</script></body></html>`;

$('.example-frame').show();
} else {
if (bpc.exampleValidVersions.length && bpc.exampleValidVersions.indexOf(bpc.majorPixiVersion) === -1) {
$('#example-title').html(
`${bpc.exampleTitle
}<br><br><br><br><br><br><br>`
`${bpc.exampleTitle}`
+ '<br><br><br><br><br><br><br>'
+ 'The selected version of PixiJS does not work with this example.'
+ '<br><br>'
+ `Selected version: v${bpc.majorPixiVersion
}<br><br>`
+ `Required version: v${bpc.exampleValidVersions.toString()
}<br><br><br><br><br>`,
+ `Selected version: v${bpc.majorPixiVersion}`
+ '<br><br>'
+ `Required version: v${bpc.exampleValidVersions.toString()}`
+ '<br><br><br><br><br>',
);

$('.example-frame').hide();
} else if (bpc.missingFeatures.length) {
$('#example-title').html(
`${bpc.exampleTitle}`
+ '<br><br><br><br><br><br><br>'
+ 'This example requires some features that your browser doesn\'t support.'
+ '<br><br>'
+ `Missing features: ${bpc.missingFeatures.join(', ')}`
+ '<br><br><br><br><br>',
);

$('.example-frame').hide();
} else {
$('#example-title').html(bpc.exampleTitle);
html += `<script>window.PIXI_WEBWORKER_URL = "${pixiWebWorkerUrl}"; window.onload = function(){${bpc.exampleSourceCode}}</script></body></html>`;

$('.example-frame').show();
}

const iframe = document.getElementById('preview');
Expand Down

0 comments on commit 4f42ecd

Please sign in to comment.