屏幕适配

与旧版相比,SpriteJS Next 简化了屏幕适配参数。

旧版在构造Scene的时候可以提供viewport和resolution两个参数,而新版不再需要手工指定viewport,而是让viewport跟随着container自适应。

新版只需要指定width/height属性,这两个属性相当于旧版里设置resolution。

粘连模式

SpriteJS Next 也对粘连模式进行了简化,不再像旧版那样有两个参数,只提供一个 mode 参数。

mode 可选值如下:

  • scale 默认值,将canvas拉伸到container大小,因为拉伸,画布可能会变形
  • stickyWidth 将canvas宽度设为container宽度,高度随比例适配,并垂直居中
  • stickyTop 将canvas宽度设为container宽度,高度随比例适配,并与container顶部对齐
  • stickyBottom 将canvas宽度设为container宽度,高度随比例适配,并与container底部对齐
  • stickyHeight 将canvas高度设为container高度,宽度随比例适配,并水平居中
  • stickyLeft 将canvas高度设为container高度,宽度随比例适配,并与container左边对齐
  • stickyRight 将canvas高度设为container高度,宽度随比例适配,并与container右边对齐
  1. const {Scene, Sprite} = spritejs;
  2. const container = document.getElementById('adaptive');
  3. const scene = new Scene({
  4. container,
  5. width: 640,
  6. height: 1000,
  7. mode: 'stickyWidth',
  8. // contextType: '2d',
  9. });
  10. const layer = scene.layer();
  11. (async function () {
  12. await scene.preload(
  13. {id: 'snow', src: 'https://p5.ssl.qhimg.com/t01bfde08606e87f1fe.png'},
  14. {id: 'cloud', src: 'https://p5.ssl.qhimg.com/t01d2ff600bae7fe897.png'}
  15. );
  16. const cloud = new Sprite('cloud');
  17. cloud.attr({
  18. anchor: [0.5, 0],
  19. pos: [320, -50],
  20. size: [200, 130],
  21. });
  22. layer.append(cloud);
  23. function addRandomSnow() {
  24. const snow = new Sprite('snow');
  25. const x0 = 20 + Math.random() * 600,
  26. y0 = 0;
  27. snow.attr({
  28. anchor: [0.5, 0.5],
  29. pos: [x0, y0],
  30. size: [50, 50],
  31. });
  32. snow.animate([
  33. {x: x0 - 10},
  34. {x: x0 + 10},
  35. ], {
  36. duration: 1000,
  37. fill: 'forwards',
  38. direction: 'alternate',
  39. iterations: Infinity,
  40. easing: 'ease-in-out',
  41. });
  42. const dropAnim = snow.animate([
  43. {y: -200, rotate: 0},
  44. {y: 2000, rotate: 1880},
  45. ], {
  46. duration: 15000,
  47. fill: 'forwards',
  48. });
  49. dropAnim.finished.then(() => {
  50. snow.remove();
  51. });
  52. layer.append(snow);
  53. }
  54. setInterval(addRandomSnow, 200);
  55. }());