MediaWiki:PauseWebpExample.js

From Heroes 3 wiki
Revision as of 17:50, 18 October 2025 by Imahero (talk | contribs)
Jump to navigation Jump to search

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';
  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');

  fetch(imageURL)
    .then(response => response.arrayBuffer())
    .then(buffer => {
      const decoder = new VideoDecoder({
        output: function (videoFrame) {
          createImageBitmap(videoFrame).then(bitmap => {
            frames.push(bitmap);
            videoFrame.close();
          });
        },
        error: function (e) {
          console.error('Decoder error:', e);
        }
      });

      decoder.configure({ codec: 'vp8' });

      const chunk = new EncodedVideoChunk({
        type: 'key',
        timestamp: 0,
        data: new Uint8Array(buffer)
      });

      decoder.decode(chunk);

      // Wait until at least one frame is decoded before starting animation
      const waitForFrames = function () {
        if (frames.length > 0) {
          drawFrame(0);
          requestAnimationFrame(animate);
        } else {
          setTimeout(waitForFrames, 50);
        }
      };

      waitForFrames();
    });

  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 (frames.length > 0) {
    const isLastFrame = currentFrame === frames.length - 1;
    const delay = isLastFrame ? 1000 : frameDuration; // 1s pause on last frame

    if (isPlaying && delta > delay) {
      currentFrame = (currentFrame + 1) % frames.length;
      drawFrame(currentFrame);
      lastUpdate = timestamp;
    }
  }

  requestAnimationFrame(animate);
}
});