Skip to content

Instantly share code, notes, and snippets.

@SnuktheGreat
Last active December 3, 2023 11:13
Show Gist options
  • Save SnuktheGreat/d995569232157e881b7e20435b8496d9 to your computer and use it in GitHub Desktop.
Save SnuktheGreat/d995569232157e881b7e20435b8496d9 to your computer and use it in GitHub Desktop.
Auto playing SVG keyframe animation

SVG file embedded with Javascript <script> to play a keyframed animation. Looks for layers named frame_X, where X is parsed as the frame number.

You can add the following HTTP query paramaters for additional control:

  • fps (default: 12)
  • reload (default: false) - Reload after one full animation

The rotating star is not the best example, since rotation can be done by SVG animations. I may update this with a proper example at some point.

Based on https://www.reddit.com/r/Inkscape/comments/ut05ra/keyframe_animation_svg_open_in_browser_to_play/

let fps = 12;
let reload = false
const frames = [];
let frameCount = 0;
function draw_frame() {
frames[frameCount].style.display = "inline";
frames[(frames.length + frameCount - 1) % frames.length].style.display = "none";
frameCount++;
if (reload && frameCount >= frames.length) {
location.reload()
}
frameCount %= frames.length;
}
function set_fps(new_fps) {
fps = new_fps
clearInterval(animate_id)
animate_id = setInterval(draw_frame, 1000 / fps);
}
function get_frame_number(el) {
return parseInt(el.getAttribute('inkscape:label').substring(6))
}
let animate_id;
window.onload = function () {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
fps = parseInt(urlParams.get("fps")) || fps;
reload = urlParams.get("reload") === "true" || false;
frames.push(...[...document.querySelectorAll(`g[*|label^=frame_]`)]
.sort((a, b) => get_frame_number(a) - get_frame_number(b)))
for (let i = 0; i < frames.length; i++) {
if (i === 0) {
frames[i].style.display = "inline";
} else {
frames[i].style.display = "none";
}
}
animate_id = setInterval(draw_frame, 1000 / fps);
};
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment