animation-state-events.html 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <link rel="stylesheet" href="../../index.css">
  7. <script src="https://unpkg.com/canvaskit-wasm@latest/bin/canvaskit.js"></script>
  8. <script src="../dist/iife/spine-canvaskit.js"></script>
  9. <style>
  10. * {
  11. margin: 0;
  12. padding: 0;
  13. }
  14. </style>
  15. </head>
  16. <body class="p-4 flex flex-col items-center">
  17. <h1>Animation State Events</h1>
  18. <p class="mb-4">Open the console in the developer tools to view events logs.</p>
  19. <canvas id=foo width=600 height=400 style="margin: 0 auto;"></canvas>
  20. </body>
  21. <script type="module">
  22. async function readFile(path) {
  23. const response = await fetch(path);
  24. if (!response.ok) throw new Error("Could not load file " + path);
  25. return await response.arrayBuffer();
  26. }
  27. const ck = await CanvasKitInit();
  28. const surface = ck.MakeCanvasSurface('foo');
  29. const atlas = await spine.loadTextureAtlas(ck, "assets/spineboy.atlas", readFile);
  30. const skeletonData = await spine.loadSkeletonData("assets/spineboy-pro.skel", atlas, readFile);
  31. const drawable = new spine.SkeletonDrawable(skeletonData);
  32. drawable.skeleton.scaleX = drawable.skeleton.scaleY = 0.4;
  33. drawable.skeleton.x = 300;
  34. drawable.skeleton.y = 380;
  35. // Set the default mix to 0.2 seconds, queue animations, and set listeners
  36. const animationState = drawable.animationState;
  37. animationState.data.defaultMix = 0.2;
  38. animationState.setAnimation(0, "walk", true).listener = {
  39. start: (entry) => console.log("Walk animation started"),
  40. end: (entry) => console.log("Walk animation ended"),
  41. };
  42. animationState.addAnimation(0, "jump", false, 2);
  43. animationState.addAnimation(0, "run", true, 0).listener = {
  44. event: (entry, event) => console.log(`Custom event "${event.data.name}"`)
  45. };
  46. animationState.addListener({
  47. completed: (entry) => console.log(`Animation ${entry.animation.name} completed`)
  48. });
  49. const renderer = new spine.SkeletonRenderer(ck);
  50. let lastTime = performance.now();
  51. function drawFrame(canvas) {
  52. canvas.clear(ck.Color(52, 52, 54, 1));
  53. const now = performance.now();
  54. const deltaTime = (now - lastTime) / 1000;
  55. lastTime = now;
  56. drawable.update(deltaTime);
  57. renderer.render(canvas, drawable);
  58. surface.requestAnimationFrame(drawFrame);
  59. }
  60. surface.requestAnimationFrame(drawFrame);
  61. </script>
  62. </html>