Snap.svg - How to load SVGs synchronous?

半世苍凉 提交于 2019-12-12 20:15:02

问题


Knowing that Snap.load(); is asynchronous, I'm looking for a way to append the loaded files in the requested order. This is the code I'm using:

s = Snap(800, 800);

function loadSvg(url) {
    Snap.load(url, appendSvg);
};

function appendSvg(svg) {
    g = svg.select("g");
    s.append(g);
};

loadSvg('https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/b.svg');
loadSvg('https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/a.svg');

I found this (http://svg.dabbles.info/snaptut-loadmulti.html), but I wonder if there's any simpler, official Snap.svg, way to do it? For me it feels that the Snap.load(); should have a feature for this included?


回答1:


You can sequence asynchronous tasks nicely with Javascript promises (polyfill for platforms that do not yet have native Promise), e.g.:

// Helper to convert Snap.load() into a Promise.
function loadSVG(url) {
  return new Promise(function(resolve, reject) {
    Snap.load(url, resolve);
  });
};

// Make an array of Promises.
var loadPromises = [
  loadSVG('http://example.com/a.svg'),
  loadSVG('http://example.com/b.svg'),
  loadSVG('http://example.com/c.svg'),
  ...
];

// Wait for all the Promises to finish.
Promise.all(loadPromises).then(function(results) {
  // results contains the loaded SVGs, in order.
  for (var i = 0; i < results.length; ++i) {
    var svg = results[i];

    // Your processing of each SVG goes here.
    var g = svg.select("g");
    s.append(g);
  }
});


来源:https://stackoverflow.com/questions/34430162/snap-svg-how-to-load-svgs-synchronous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!