-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathtoimage.js
82 lines (62 loc) · 2.31 KB
/
toimage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*eslint dot-notation: [2, {"allowPattern": "^catch$"}]*/
'use strict';
var EventEmitter = require('events').EventEmitter;
var Plotly = require('../plotly');
/**
* @param {object} gd figure Object
* @param {object} opts option object
* @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
*/
function toImage(gd, opts) {
// first clone the GD so we can operate in a clean environment
var Snapshot = Plotly.Snapshot;
var ev = new EventEmitter();
var clone = Snapshot.clone(gd, {format: 'png'});
var clonedGd = clone.td;
// put the cloned div somewhere off screen before attaching to DOM
clonedGd.style.position = 'absolute';
clonedGd.style.left = '-5000px';
document.body.appendChild(clonedGd);
function wait() {
var delay = Snapshot.getDelay(clonedGd._fullLayout);
setTimeout(function() {
var svg = Plotly.Snapshot.toSVG(clonedGd);
var canvasContainer = window.document.createElement('div');
var canvas = window.document.createElement('canvas');
// window.document.body.appendChild(canvasContainer);
canvasContainer.appendChild(canvas);
canvasContainer.id = Plotly.Lib.randstr();
canvas.id = Plotly.Lib.randstr();
ev = Plotly.Snapshot.svgToImg({
format: opts.format,
width: clonedGd._fullLayout.width,
height: clonedGd._fullLayout.height,
canvas: canvas,
emitter: ev,
svg: svg
});
ev.clean = function() {
if(clonedGd) clonedGd.remove();
};
}, delay);
}
var redrawFunc = Snapshot.getRedrawFunc(clonedGd);
Plotly.plot(clonedGd, clone.data, clone.layout, clone.config)
// TODO: the following is Plotly.Plots.redrawText but without the waiting.
// we shouldn't need to do this, but in *occasional* cases we do. Figure
// out why and take it out.
.then(redrawFunc)
.then(wait)
.catch(function(err) {
ev.emit('error', err);
});
return ev;
}
module.exports = toImage;