Subversion-Projekte lars-tiefland.cienc

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
9 lars 1
/**
2
 * @license Highstock JS v2.1.8 (2015-08-20)
3
 * Client side exporting module
4
 *
5
 * (c) 2015 Torstein Honsi / Oystein Moseng
6
 *
7
 * License: www.highcharts.com/license
8
 */
9
 
10
// JSLint options:
11
/*global Highcharts, HighchartsAdapter, document, window, Blob, MSBlobBuilder */
12
 
13
(function (Highcharts) {
14
 
15
// Dummy object so we can reuse our canvas-tools.js without errors
16
Highcharts.CanVGRenderer = {};
17
 
18
/**
19
 * Add a new method to the Chart object to perform a local download
20
 */
21
Highcharts.Chart.prototype.exportChartLocal = function (exportingOptions, chartOptions) {
22
	var chart = this,
23
		options = Highcharts.merge(chart.options.exporting, exportingOptions),
24
		webKit = navigator.userAgent.indexOf('WebKit') > -1 && navigator.userAgent.indexOf("Chrome") < 0, // Webkit and not chrome
25
		scale = options.scale || 2,
26
		chartCopyContainer,
27
		domurl = window.URL || window.webkitURL || window,
28
		images,
29
		imagesEmbedded = 0,
30
		el,
31
		i,
32
		l,
33
		fallbackToExportServer = function () {
34
			if (options.fallbackToExportServer === false) {
35
				throw 'Fallback to export server disabled';
36
			}
37
			chart.exportChart(options);
38
		},
39
		// Get data:URL from image URL
40
		// Pass in callbacks to handle results. finallyCallback is always called at the end of the process. Supplying this callback is optional.
41
		// All callbacks receive two arguments: imageURL, and callbackArgs. callbackArgs is used only by callbacks and can contain whatever.
42
		imageToDataUrl = function (imageURL, callbackArgs, successCallback, taintedCallback, noCanvasSupportCallback, failedLoadCallback, finallyCallback) {
43
			var img = new Image();
44
			if (!webKit) {
45
				img.crossOrigin = 'Anonymous'; // For some reason Safari chokes on this attribute
46
			}
47
			img.onload = function () {
48
				var canvas = document.createElement('canvas'),
49
					ctx = canvas.getContext && canvas.getContext('2d'),
50
					dataURL;
51
 
52
				if (!ctx) {
53
					noCanvasSupportCallback(imageURL, callbackArgs);
54
				} else {
55
					canvas.height = img.height * scale;
56
					canvas.width = img.width * scale;
57
					ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
58
 
59
					// Now we try to get the contents of the canvas.
60
					try {
61
						dataURL = canvas.toDataURL();
62
						successCallback(dataURL, callbackArgs);
63
					} catch (e) {
64
						// Failed - either tainted canvas or something else went horribly wrong
65
						if (e.name === 'SecurityError' || e.name === 'SECURITY_ERR' || e.message === 'SecurityError') {
66
							taintedCallback(imageURL, callbackArgs);
67
						} else {
68
							throw e;
69
						}
70
					}
71
				}
72
				if (finallyCallback) {
73
					finallyCallback(imageURL, callbackArgs);
74
				}
75
			};
76
			img.onerror = function () {
77
				failedLoadCallback(imageURL, callbackArgs);
78
				if (finallyCallback) {
79
					finallyCallback(imageURL, callbackArgs);
80
				}
81
			};
82
			img.src = imageURL;
83
		},
84
		// Get blob URL from SVG code. Falls back to normal data URI.
85
		svgToDataUrl = function (svg) {
86
			try {
87
				// Safari requires data URI since it doesn't allow navigation to blob URLs
88
				if (!webKit) {
89
					return domurl.createObjectURL(new Blob([svg], { type: 'image/svg+xml;charset-utf-16'}));
90
				}
91
			} catch (e) {
92
				// Ignore
93
			}
94
			return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
95
		},
96
		// Download contents by dataURL/blob
97
		download = function (dataURL, extension) {
98
			var a = document.createElement('a'),
99
				filename = (options.filename || 'chart') + '.' + extension,
100
				windowRef;
101
 
102
			// IE specific blob implementation
103
			if (navigator.msSaveOrOpenBlob) {
104
				navigator.msSaveOrOpenBlob(dataURL, filename);
105
				return;
106
			}
107
 
108
			// Try HTML5 download attr if supported
109
			if (typeof a.download !== 'undefined') {
110
				a.href = dataURL;
111
				a.download = filename; // HTML5 download attribute
112
				a.target = '_blank';
113
				document.body.appendChild(a);
114
				a.click();
115
				document.body.removeChild(a);
116
			} else {
117
				// No download attr, just opening data URI
118
				try {
119
					windowRef = window.open(dataURL, 'chart');
120
					if (typeof windowRef === 'undefined' || windowRef === null) {
121
						throw 1;
122
					}
123
				} catch (e) {
124
					// window.open failed, trying location.href
125
					window.location.href = dataURL;
126
				}
127
			}
128
		},
129
		// Get data URL to an image of the chart and call download on it
130
		initiateDownload = function () {
131
			var svgurl,
132
				blob,
133
				svg = chart.sanitizeSVG(chartCopyContainer.innerHTML); // SVG of chart copy
134
 
135
			// Initiate download depending on file type
136
			if (options && options.type === 'image/svg+xml') {
137
				// SVG download. In this case, we want to use Microsoft specific Blob if available
138
				try {
139
					if (navigator.msSaveOrOpenBlob) {
140
						blob = new MSBlobBuilder();
141
						blob.append(svg);
142
						svgurl = blob.getBlob('image/svg+xml');
143
					} else {
144
						svgurl = svgToDataUrl(svg);
145
					}
146
					download(svgurl, 'svg');
147
				} catch (e) {
148
					fallbackToExportServer();
149
				}
150
			} else {
151
				// PNG download - create bitmap from SVG
152
 
153
				// First, try to get PNG by rendering on canvas
154
				svgurl = svgToDataUrl(svg);
155
				imageToDataUrl(svgurl, { /* args */ }, function (imageURL) {
156
					// Success
157
					try {
158
						download(imageURL, 'png');
159
					} catch (e) {
160
						fallbackToExportServer();
161
					}
162
				}, function () {
163
					// Failed due to tainted canvas
164
					// Create new and untainted canvas
165
					var canvas = document.createElement('canvas'),
166
						ctx = canvas.getContext('2d'),
167
						imageWidth = svg.match(/^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/)[1] * scale,
168
						imageHeight = svg.match(/^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/)[1] * scale,
169
						downloadWithCanVG = function () {
170
							ctx.drawSvg(svg, 0, 0, imageWidth, imageHeight);
171
							try {
172
								download(navigator.msSaveOrOpenBlob ? canvas.msToBlob() : canvas.toDataURL('image/png'), 'png');
173
							} catch (e) {
174
								fallbackToExportServer();
175
							}
176
						};
177
 
178
					canvas.width = imageWidth;
179
					canvas.height = imageHeight;
180
					if (window.canvg) {
181
						// Use preloaded canvg
182
						downloadWithCanVG();
183
					} else {
184
						// Must load canVG first
185
						chart.showLoading();
186
						HighchartsAdapter.getScript(Highcharts.getOptions().global.canvasToolsURL, function () {
187
							chart.hideLoading();
188
							downloadWithCanVG();
189
						});
190
					}
191
				},
192
				// No canvas support
193
				fallbackToExportServer,
194
				// Failed to load image
195
				fallbackToExportServer,
196
				// Finally
197
				function () {
198
					try {
199
						domurl.revokeObjectURL(svgurl);
200
					} catch (e) {
201
						// Ignore
202
					}
203
				});
204
			}
205
		};
206
 
207
	// Hook into getSVG to get a copy of the chart copy's container
208
	Highcharts.wrap(Highcharts.Chart.prototype, 'getChartHTML', function (proceed) {
209
		chartCopyContainer = this.container.cloneNode(true);
210
		return proceed.apply(this, Array.prototype.slice.call(arguments, 1));
211
	});
212
 
213
	// Trigger hook to get chart copy
214
	chart.getSVGForExport(options, chartOptions);
215
	images = chartCopyContainer.getElementsByTagName('image');
216
 
217
	try {
218
		// If there are no images to embed, just go ahead and start the download process
219
		if (!images.length) {
220
			initiateDownload();
221
		}
222
 
223
		// Success handler, we converted image to base64!
224
		function embeddedSuccess(imageURL, callbackArgs) {
225
			++imagesEmbedded;
226
 
227
			// Change image href in chart copy
228
			callbackArgs.imageElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', imageURL);
229
 
230
			// Start download when done with the last image
231
			if (imagesEmbedded === images.length) {
232
				initiateDownload();
233
			}
234
		}
235
 
236
		// Go through the images we want to embed
237
		for (i = 0, l = images.length; i < l; ++i) {
238
			el = images[i];
239
			imageToDataUrl(el.getAttributeNS('http://www.w3.org/1999/xlink', 'href'), { imageElement: el },
240
				embeddedSuccess,
241
				// Tainted canvas
242
				fallbackToExportServer,
243
				// No canvas support
244
				fallbackToExportServer,
245
				// Failed to load source
246
				fallbackToExportServer
247
			);
248
		}
249
	} catch (e) {
250
		fallbackToExportServer();
251
	}
252
};
253
 
254
// Extend the default options to use the local exporter logic
255
Highcharts.getOptions().exporting.buttons.contextButton.menuItems = [{
256
	textKey: 'printChart',
257
	onclick: function () {
258
		this.print();
259
	}
260
}, {
261
	separator: true
262
}, {
263
	textKey: 'downloadPNG',
264
	onclick: function () {
265
		this.exportChartLocal();
266
	}
267
}, {
268
	textKey: 'downloadSVG',
269
	onclick: function () {
270
		this.exportChartLocal({
271
			type: 'image/svg+xml'
272
		});
273
	}
274
}];
275
 
276
}(Highcharts));