mirror of
https://github.com/scratchfoundation/paper.js.git
synced 2025-01-01 02:38:43 -05:00
SvgImport: Implement support for onLoad and onError callbacks on string input.
Closes #827
This commit is contained in:
parent
2025bd1a77
commit
75c40babc9
1 changed files with 26 additions and 19 deletions
|
@ -640,22 +640,32 @@ new function() {
|
|||
return null;
|
||||
options = typeof options === 'function' ? { onLoad: options }
|
||||
: options || {};
|
||||
var node = source,
|
||||
// Remember current scope so we can restore it in onLoad.
|
||||
scope = paper;
|
||||
// Remember current scope so we can restore it in onLoad.
|
||||
var scope = paper,
|
||||
item = null;
|
||||
|
||||
function onLoad(svg) {
|
||||
paper = scope;
|
||||
var item = importSVG(svg, options, true),
|
||||
onLoad = options.onLoad;
|
||||
if (onLoad)
|
||||
onLoad.call(this, item, svg);
|
||||
try {
|
||||
var node = typeof svg === 'object' ? svg : new window.DOMParser()
|
||||
.parseFromString(svg, 'image/svg+xml');
|
||||
if (!node.nodeName) {
|
||||
node = null;
|
||||
throw new Error('Unsupported SVG source: ' + source);
|
||||
}
|
||||
paper = scope;
|
||||
item = importNode(node, options, true);
|
||||
var onLoad = options.onLoad;
|
||||
if (onLoad)
|
||||
onLoad(item, svg);
|
||||
} catch (e) {
|
||||
onError(e);
|
||||
}
|
||||
}
|
||||
|
||||
function onError(message, status) {
|
||||
var onError = options.onError;
|
||||
if (onError) {
|
||||
onError.call(this, message, status);
|
||||
onError(message, status);
|
||||
} else {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
@ -667,15 +677,16 @@ new function() {
|
|||
if (typeof source === 'string' && !/^.*</.test(source)) {
|
||||
// First see if we're meant to import an element with the given
|
||||
// id.
|
||||
node = document.getElementById(source);
|
||||
var node = document.getElementById(source);
|
||||
// Check if the string does not represent SVG data, in which
|
||||
// case it must be the URL of a SVG to be loaded.
|
||||
if (node) {
|
||||
source = null;
|
||||
onLoad(node);
|
||||
} else {
|
||||
Http.request({
|
||||
url: source, async: true,
|
||||
onLoad: onLoad, onError: onError
|
||||
onLoad: onLoad,
|
||||
onError: onError
|
||||
});
|
||||
}
|
||||
} else if (typeof File !== 'undefined' && source instanceof File) {
|
||||
|
@ -688,15 +699,11 @@ new function() {
|
|||
onError(reader.error);
|
||||
};
|
||||
return reader.readAsText(source);
|
||||
} else {
|
||||
onLoad(source);
|
||||
}
|
||||
|
||||
if (typeof source === 'string') {
|
||||
node = new window.DOMParser().parseFromString(source,
|
||||
'image/svg+xml');
|
||||
}
|
||||
if (!node.nodeName)
|
||||
throw new Error('Unsupported SVG source: ' + source);
|
||||
return importNode(node, options, true);
|
||||
return item;
|
||||
}
|
||||
|
||||
// NOTE: Documentation is in Item#importSVG()
|
||||
|
|
Loading…
Reference in a new issue