Snap.svg - 如何同步加载 SVG? [英] Snap.svg - How to load SVGs synchronous?

查看:64
本文介绍了Snap.svg - 如何同步加载 SVG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

知道 Snap.load(); 是异步的,我正在寻找一种方法来按请求的顺序附加加载的文件.这是我正在使用的代码:

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');

我发现了这个(http://svg.dabbles.info/snaptut-loadmulti.html),但我想知道是否有任何更简单的官方 Snap.svg 方法来做到这一点?对我来说,我觉得 Snap.load(); 应该有一个功能吗?

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?

推荐答案

您可以使用 Javascript 承诺(polyfill还没有原生 Promise 的平台),例如:

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);
  }
});

这篇关于Snap.svg - 如何同步加载 SVG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆