快照

每个layer有自己的context,如果我们的scene有多个layer,而且我们需要将scene当前绘制结果保存下来时,我们并不需要自己处理每个layer(尽管自己处理也是可以的,通过layer.canvas可以拿到layer的canvas对象)。

SpriteJS Next 提供了一个同步的接口snapshot(),我们可以给scene拍一个当前的“快照”,snapshot()返回一个canvas对象,这个canvas对象是当前所有layer输出内容的叠加。

  1. const {Scene, Sprite, Path} = spritejs;
  2. const container = document.getElementById('adaptive');
  3. const scene = new Scene({
  4. container,
  5. width: 1200,
  6. height: 600,
  7. });
  8. const bglayer = scene.layer('bglayer');
  9. const fglayer = scene.layer('fglayer');
  10. (async function () {
  11. function randomTriangle() {
  12. const triangle = new Path();
  13. const pos = [Math.random() * 1540, Math.random() * 600];
  14. const d = 'M0,0L0,10L8.66, 5z';
  15. triangle.attr({
  16. d,
  17. scale: 5,
  18. pos,
  19. fillColor: '#37c',
  20. rotate: Math.random() * 360,
  21. });
  22. bglayer.append(triangle);
  23. }
  24. for(let i = 0; i < 100; i++) {
  25. randomTriangle();
  26. }
  27. const birdsJsonUrl = 'https://s5.ssl.qhres.com/static/5f6911b7b91c88da.json';
  28. const birdsRes = 'https://p.ssl.qhimg.com/d/inn/c886d09f/birds.png';
  29. await scene.preload([birdsRes, birdsJsonUrl]);
  30. const bird = new Sprite('bird1.png');
  31. bird.attr({
  32. anchor: [0.5, 0.5],
  33. pos: [50, 200],
  34. scale: 0.6,
  35. offsetPath: 'M0,100C0,100,200,-100,500,100S700,-100,1000,100S1200,-100,1700,100S2200,-100,2700,100',
  36. });
  37. fglayer.append(bird);
  38. bird.animate([
  39. {texture: 'bird1.png'},
  40. {texture: 'bird2.png'},
  41. {texture: 'bird3.png'},
  42. {texture: 'bird1.png'},
  43. ], {
  44. duration: 300,
  45. iterations: Infinity,
  46. direction: 'alternate',
  47. easing: 'step-end',
  48. });
  49. bird.animate([
  50. {offsetDistance: 0},
  51. {offsetDistance: 1},
  52. ], {
  53. duration: 6000,
  54. iterations: Infinity,
  55. });
  56. const snapshotBtn = document.getElementById('take-snapshot'),
  57. snapshotList = document.getElementById('snapshot-list');
  58. snapshotBtn.addEventListener('click', (evt) => {
  59. const canvas = scene.snapshot();
  60. const snapshot = new Image();
  61. snapshot.src = canvas.toDataURL();
  62. const listItem = document.createElement('li');
  63. listItem.appendChild(snapshot);
  64. snapshotList.appendChild(listItem);
  65. });
  66. }());

离屏快照

调用Scene的snapshot方法时,如果传参{offscreen: true},那么快照将返回一个OffscreenCanvas