MediaWiki:PauseWebpExample.js
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
$(function () {
const canvas = $('<canvas>', {
id: 'pikemanCanvas',
width: 64,
height: 64,
css: { border: '1px solid #ccc', display: 'block', margin: '10px 0' }
}).appendTo('#bodyContent')[0];
const ctx = canvas.getContext('2d');
const imageURL = 'https://heroes.thelazy.net/images/f/f1/Pikeman.webp'; // animated WebP
const frames = [];
let currentFrame = 0;
let isPlaying = true;
let frameDuration = 100;
let lastUpdate = 0;
window.togglePikemanAnimation = function () {
isPlaying = !isPlaying;
};
$('<button>', {
text: 'Pause/Play',
click: window.togglePikemanAnimation
}).appendTo('#bodyContent');
(async function () {
const response = await fetch(imageURL);
const buffer = await response.arrayBuffer();
const decoder = new VideoDecoder({
output: handleFrame,
error: e => console.error('Decoder error:', e)
});
decoder.configure({ codec: 'vp8' });
// Feed the entire buffer as a single chunk
const chunk = new EncodedVideoChunk({
type: 'key',
timestamp: 0,
data: new Uint8Array(buffer)
});
decoder.decode(chunk);
function handleFrame(videoFrame) {
createImageBitmap(videoFrame).then(bitmap => {
frames.push(bitmap);
videoFrame.close();
});
}
// Wait for decoding to finish
const waitForFrames = () => new Promise(resolve => {
const check = () => {
if (frames.length > 0) resolve();
else setTimeout(check, 50);
};
check();
});
await waitForFrames();
drawFrame(0);
requestAnimationFrame(animate);
})();
function drawFrame(index) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(frames[index], 0, 0, canvas.width, canvas.height);
}
function animate(timestamp) {
if (!lastUpdate) lastUpdate = timestamp;
const delta = timestamp - lastUpdate;
if (isPlaying && delta > frameDuration && frames.length > 0) {
currentFrame = (currentFrame + 1) % frames.length;
drawFrame(currentFrame);
lastUpdate = timestamp;
}
requestAnimationFrame(animate);
}
});