BoostCanvas.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /* *
  2. *
  3. * License: www.highcharts.com/license
  4. * Author: Torstein Honsi, Christer Vasseng
  5. *
  6. * This module serves as a fallback for the Boost module in IE9 and IE10. Newer
  7. * browsers support WebGL which is faster.
  8. *
  9. * It is recommended to include this module in conditional comments targeting
  10. * IE9 and IE10.
  11. *
  12. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  13. *
  14. * */
  15. 'use strict';
  16. import Chart from '../Core/Chart/Chart.js';
  17. import Color from '../Core/Color/Color.js';
  18. var color = Color.parse;
  19. import H from '../Core/Globals.js';
  20. var doc = H.doc, noop = H.noop;
  21. import LineSeries from '../Series/LineSeries.js';
  22. import Series from '../Core/Series/Series.js';
  23. import U from '../Core/Utilities.js';
  24. var addEvent = U.addEvent, extend = U.extend, fireEvent = U.fireEvent, isNumber = U.isNumber, merge = U.merge, pick = U.pick, wrap = U.wrap;
  25. import '../Core/Options.js';
  26. var seriesTypes = Series.seriesTypes, CHUNK_SIZE = 50000, destroyLoadingDiv;
  27. /* eslint-disable no-invalid-this, valid-jsdoc */
  28. /**
  29. * Initialize the canvas boost.
  30. *
  31. * @function Highcharts.initCanvasBoost
  32. */
  33. var initCanvasBoost = function () {
  34. if (H.seriesTypes.heatmap) {
  35. wrap(H.seriesTypes.heatmap.prototype, 'drawPoints', function () {
  36. var chart = this.chart, ctx = this.getContext(), inverted = this.chart.inverted, xAxis = this.xAxis, yAxis = this.yAxis;
  37. if (ctx) {
  38. // draw the columns
  39. this.points.forEach(function (point) {
  40. var plotY = point.plotY, shapeArgs, pointAttr;
  41. if (typeof plotY !== 'undefined' &&
  42. !isNaN(plotY) &&
  43. point.y !== null) {
  44. shapeArgs = point.shapeArgs;
  45. if (!chart.styledMode) {
  46. pointAttr = point.series.pointAttribs(point);
  47. }
  48. else {
  49. pointAttr = point.series.colorAttribs(point);
  50. }
  51. ctx.fillStyle = pointAttr.fill;
  52. if (inverted) {
  53. ctx.fillRect(yAxis.len - shapeArgs.y + xAxis.left, xAxis.len - shapeArgs.x + yAxis.top, -shapeArgs.height, -shapeArgs.width);
  54. }
  55. else {
  56. ctx.fillRect(shapeArgs.x + xAxis.left, shapeArgs.y + yAxis.top, shapeArgs.width, shapeArgs.height);
  57. }
  58. }
  59. });
  60. this.canvasToSVG();
  61. }
  62. else {
  63. this.chart.showLoading('Your browser doesn\'t support HTML5 canvas, <br>' +
  64. 'please use a modern browser');
  65. // Uncomment this to provide low-level (slow) support in oldIE.
  66. // It will cause script errors on charts with more than a few
  67. // thousand points.
  68. // arguments[0].call(this);
  69. }
  70. });
  71. }
  72. extend(LineSeries.prototype, {
  73. /**
  74. * Create a hidden canvas to draw the graph on. The contents is later
  75. * copied over to an SVG image element.
  76. *
  77. * @private
  78. * @function Highcharts.Series#getContext
  79. */
  80. getContext: function () {
  81. var chart = this.chart, width = chart.chartWidth, height = chart.chartHeight, targetGroup = chart.seriesGroup || this.group, target = this, ctx, swapXY = function (proceed, x, y, a, b, c, d) {
  82. proceed.call(this, y, x, a, b, c, d);
  83. };
  84. if (chart.isChartSeriesBoosting()) {
  85. target = chart;
  86. targetGroup = chart.seriesGroup;
  87. }
  88. ctx = target.ctx;
  89. if (!target.canvas) {
  90. target.canvas = doc.createElement('canvas');
  91. target.renderTarget = chart.renderer
  92. .image('', 0, 0, width, height)
  93. .addClass('highcharts-boost-canvas')
  94. .add(targetGroup);
  95. target.ctx = ctx = target.canvas.getContext('2d');
  96. if (chart.inverted) {
  97. ['moveTo', 'lineTo', 'rect', 'arc'].forEach(function (fn) {
  98. wrap(ctx, fn, swapXY);
  99. });
  100. }
  101. target.boostCopy = function () {
  102. target.renderTarget.attr({
  103. href: target.canvas.toDataURL('image/png')
  104. });
  105. };
  106. target.boostClear = function () {
  107. ctx.clearRect(0, 0, target.canvas.width, target.canvas.height);
  108. if (target === this) {
  109. target.renderTarget.attr({ href: '' });
  110. }
  111. };
  112. target.boostClipRect = chart.renderer.clipRect();
  113. target.renderTarget.clip(target.boostClipRect);
  114. }
  115. else if (!(target instanceof H.Chart)) {
  116. // ctx.clearRect(0, 0, width, height);
  117. }
  118. if (target.canvas.width !== width) {
  119. target.canvas.width = width;
  120. }
  121. if (target.canvas.height !== height) {
  122. target.canvas.height = height;
  123. }
  124. target.renderTarget.attr({
  125. x: 0,
  126. y: 0,
  127. width: width,
  128. height: height,
  129. style: 'pointer-events: none',
  130. href: ''
  131. });
  132. target.boostClipRect.attr(chart.getBoostClipRect(target));
  133. return ctx;
  134. },
  135. /**
  136. * Draw the canvas image inside an SVG image
  137. *
  138. * @private
  139. * @function Highcharts.Series#canvasToSVG
  140. */
  141. canvasToSVG: function () {
  142. if (!this.chart.isChartSeriesBoosting()) {
  143. if (this.boostCopy || this.chart.boostCopy) {
  144. (this.boostCopy || this.chart.boostCopy)();
  145. }
  146. }
  147. else {
  148. if (this.boostClear) {
  149. this.boostClear();
  150. }
  151. }
  152. },
  153. cvsLineTo: function (ctx, clientX, plotY) {
  154. ctx.lineTo(clientX, plotY);
  155. },
  156. renderCanvas: function () {
  157. var series = this, options = series.options, chart = series.chart, xAxis = this.xAxis, yAxis = this.yAxis, activeBoostSettings = chart.options.boost || {}, boostSettings = {
  158. timeRendering: activeBoostSettings.timeRendering || false,
  159. timeSeriesProcessing: activeBoostSettings.timeSeriesProcessing || false,
  160. timeSetup: activeBoostSettings.timeSetup || false
  161. }, ctx, c = 0, xData = series.processedXData, yData = series.processedYData, rawData = options.data, xExtremes = xAxis.getExtremes(), xMin = xExtremes.min, xMax = xExtremes.max, yExtremes = yAxis.getExtremes(), yMin = yExtremes.min, yMax = yExtremes.max, pointTaken = {}, lastClientX, sampling = !!series.sampling, points, r = options.marker && options.marker.radius, cvsDrawPoint = this.cvsDrawPoint, cvsLineTo = options.lineWidth ? this.cvsLineTo : void 0, cvsMarker = (r && r <= 1 ?
  162. this.cvsMarkerSquare :
  163. this.cvsMarkerCircle), strokeBatch = this.cvsStrokeBatch || 1000, enableMouseTracking = options.enableMouseTracking !== false, lastPoint, threshold = options.threshold, yBottom = yAxis.getThreshold(threshold), hasThreshold = isNumber(threshold), translatedThreshold = yBottom, doFill = this.fill, isRange = (series.pointArrayMap &&
  164. series.pointArrayMap.join(',') === 'low,high'), isStacked = !!options.stacking, cropStart = series.cropStart || 0, loadingOptions = chart.options.loading, requireSorting = series.requireSorting, wasNull, connectNulls = options.connectNulls, useRaw = !xData, minVal, maxVal, minI, maxI, index, sdata = (isStacked ?
  165. series.data :
  166. (xData || rawData)), fillColor = (series.fillOpacity ?
  167. new Color(series.color).setOpacity(pick(options.fillOpacity, 0.75)).get() :
  168. series.color),
  169. //
  170. stroke = function () {
  171. if (doFill) {
  172. ctx.fillStyle = fillColor;
  173. ctx.fill();
  174. }
  175. else {
  176. ctx.strokeStyle = series.color;
  177. ctx.lineWidth = options.lineWidth;
  178. ctx.stroke();
  179. }
  180. },
  181. //
  182. drawPoint = function (clientX, plotY, yBottom, i) {
  183. if (c === 0) {
  184. ctx.beginPath();
  185. if (cvsLineTo) {
  186. ctx.lineJoin = 'round';
  187. }
  188. }
  189. if (chart.scroller &&
  190. series.options.className ===
  191. 'highcharts-navigator-series') {
  192. plotY += chart.scroller.top;
  193. if (yBottom) {
  194. yBottom += chart.scroller.top;
  195. }
  196. }
  197. else {
  198. plotY += chart.plotTop;
  199. }
  200. clientX += chart.plotLeft;
  201. if (wasNull) {
  202. ctx.moveTo(clientX, plotY);
  203. }
  204. else {
  205. if (cvsDrawPoint) {
  206. cvsDrawPoint(ctx, clientX, plotY, yBottom, lastPoint);
  207. }
  208. else if (cvsLineTo) {
  209. cvsLineTo(ctx, clientX, plotY);
  210. }
  211. else if (cvsMarker) {
  212. cvsMarker.call(series, ctx, clientX, plotY, r, i);
  213. }
  214. }
  215. // We need to stroke the line for every 1000 pixels. It will
  216. // crash the browser memory use if we stroke too
  217. // infrequently.
  218. c = c + 1;
  219. if (c === strokeBatch) {
  220. stroke();
  221. c = 0;
  222. }
  223. // Area charts need to keep track of the last point
  224. lastPoint = {
  225. clientX: clientX,
  226. plotY: plotY,
  227. yBottom: yBottom
  228. };
  229. },
  230. //
  231. compareX = options.findNearestPointBy === 'x',
  232. //
  233. xDataFull = (this.xData ||
  234. this.options.xData ||
  235. this.processedXData ||
  236. false),
  237. //
  238. addKDPoint = function (clientX, plotY, i) {
  239. // Shaves off about 60ms compared to repeated concatenation
  240. index = compareX ? clientX : clientX + ',' + plotY;
  241. // The k-d tree requires series points.
  242. // Reduce the amount of points, since the time to build the
  243. // tree increases exponentially.
  244. if (enableMouseTracking && !pointTaken[index]) {
  245. pointTaken[index] = true;
  246. if (chart.inverted) {
  247. clientX = xAxis.len - clientX;
  248. plotY = yAxis.len - plotY;
  249. }
  250. points.push({
  251. x: xDataFull ?
  252. xDataFull[cropStart + i] :
  253. false,
  254. clientX: clientX,
  255. plotX: clientX,
  256. plotY: plotY,
  257. i: cropStart + i
  258. });
  259. }
  260. };
  261. if (this.renderTarget) {
  262. this.renderTarget.attr({ 'href': '' });
  263. }
  264. // If we are zooming out from SVG mode, destroy the graphics
  265. if (this.points || this.graph) {
  266. this.destroyGraphics();
  267. }
  268. // The group
  269. series.plotGroup('group', 'series', series.visible ? 'visible' : 'hidden', options.zIndex, chart.seriesGroup);
  270. series.markerGroup = series.group;
  271. addEvent(series, 'destroy', function () {
  272. // Prevent destroy twice
  273. series.markerGroup = null;
  274. });
  275. points = this.points = [];
  276. ctx = this.getContext();
  277. series.buildKDTree = noop; // Do not start building while drawing
  278. if (this.boostClear) {
  279. this.boostClear();
  280. }
  281. // if (this.canvas) {
  282. // ctx.clearRect(
  283. // 0,
  284. // 0,
  285. // this.canvas.width,
  286. // this.canvas.height
  287. // );
  288. // }
  289. if (!this.visible) {
  290. return;
  291. }
  292. // Display a loading indicator
  293. if (rawData.length > 99999) {
  294. chart.options.loading = merge(loadingOptions, {
  295. labelStyle: {
  296. backgroundColor: color('#ffffff').setOpacity(0.75).get(),
  297. padding: '1em',
  298. borderRadius: '0.5em'
  299. },
  300. style: {
  301. backgroundColor: 'none',
  302. opacity: 1
  303. }
  304. });
  305. U.clearTimeout(destroyLoadingDiv);
  306. chart.showLoading('Drawing...');
  307. chart.options.loading = loadingOptions; // reset
  308. }
  309. if (boostSettings.timeRendering) {
  310. console.time('canvas rendering'); // eslint-disable-line no-console
  311. }
  312. // Loop over the points
  313. H.eachAsync(sdata, function (d, i) {
  314. var x, y, clientX, plotY, isNull, low, isNextInside = false, isPrevInside = false, nx = false, px = false, chartDestroyed = typeof chart.index === 'undefined', isYInside = true;
  315. if (!chartDestroyed) {
  316. if (useRaw) {
  317. x = d[0];
  318. y = d[1];
  319. if (sdata[i + 1]) {
  320. nx = sdata[i + 1][0];
  321. }
  322. if (sdata[i - 1]) {
  323. px = sdata[i - 1][0];
  324. }
  325. }
  326. else {
  327. x = d;
  328. y = yData[i];
  329. if (sdata[i + 1]) {
  330. nx = sdata[i + 1];
  331. }
  332. if (sdata[i - 1]) {
  333. px = sdata[i - 1];
  334. }
  335. }
  336. if (nx && nx >= xMin && nx <= xMax) {
  337. isNextInside = true;
  338. }
  339. if (px && px >= xMin && px <= xMax) {
  340. isPrevInside = true;
  341. }
  342. // Resolve low and high for range series
  343. if (isRange) {
  344. if (useRaw) {
  345. y = d.slice(1, 3);
  346. }
  347. low = y[0];
  348. y = y[1];
  349. }
  350. else if (isStacked) {
  351. x = d.x;
  352. y = d.stackY;
  353. low = y - d.y;
  354. }
  355. isNull = y === null;
  356. // Optimize for scatter zooming
  357. if (!requireSorting) {
  358. isYInside = y >= yMin && y <= yMax;
  359. }
  360. if (!isNull &&
  361. ((x >= xMin && x <= xMax && isYInside) ||
  362. (isNextInside || isPrevInside))) {
  363. clientX = Math.round(xAxis.toPixels(x, true));
  364. if (sampling) {
  365. if (typeof minI === 'undefined' ||
  366. clientX === lastClientX) {
  367. if (!isRange) {
  368. low = y;
  369. }
  370. if (typeof maxI === 'undefined' || y > maxVal) {
  371. maxVal = y;
  372. maxI = i;
  373. }
  374. if (typeof minI === 'undefined' ||
  375. low < minVal) {
  376. minVal = low;
  377. minI = i;
  378. }
  379. }
  380. // Add points and reset
  381. if (clientX !== lastClientX) {
  382. // maxI also a number:
  383. if (typeof minI !== 'undefined') {
  384. plotY = yAxis.toPixels(maxVal, true);
  385. yBottom = yAxis.toPixels(minVal, true);
  386. drawPoint(clientX, hasThreshold ?
  387. Math.min(plotY, translatedThreshold) : plotY, hasThreshold ?
  388. Math.max(yBottom, translatedThreshold) : yBottom, i);
  389. addKDPoint(clientX, plotY, maxI);
  390. if (yBottom !== plotY) {
  391. addKDPoint(clientX, yBottom, minI);
  392. }
  393. }
  394. minI = maxI = void 0;
  395. lastClientX = clientX;
  396. }
  397. }
  398. else {
  399. plotY = Math.round(yAxis.toPixels(y, true));
  400. drawPoint(clientX, plotY, yBottom, i);
  401. addKDPoint(clientX, plotY, i);
  402. }
  403. }
  404. wasNull = isNull && !connectNulls;
  405. if (i % CHUNK_SIZE === 0) {
  406. if (series.boostCopy || series.chart.boostCopy) {
  407. (series.boostCopy || series.chart.boostCopy)();
  408. }
  409. }
  410. }
  411. return !chartDestroyed;
  412. }, function () {
  413. var loadingDiv = chart.loadingDiv, loadingShown = chart.loadingShown;
  414. stroke();
  415. // if (series.boostCopy || series.chart.boostCopy) {
  416. // (series.boostCopy || series.chart.boostCopy)();
  417. // }
  418. series.canvasToSVG();
  419. if (boostSettings.timeRendering) {
  420. console.timeEnd('canvas rendering'); // eslint-disable-line no-console
  421. }
  422. fireEvent(series, 'renderedCanvas');
  423. // Do not use chart.hideLoading, as it runs JS animation and
  424. // will be blocked by buildKDTree. CSS animation looks good, but
  425. // then it must be deleted in timeout. If we add the module to
  426. // core, change hideLoading so we can skip this block.
  427. if (loadingShown) {
  428. extend(loadingDiv.style, {
  429. transition: 'opacity 250ms',
  430. opacity: 0
  431. });
  432. chart.loadingShown = false;
  433. destroyLoadingDiv = setTimeout(function () {
  434. if (loadingDiv.parentNode) { // In exporting it is falsy
  435. loadingDiv.parentNode.removeChild(loadingDiv);
  436. }
  437. chart.loadingDiv = chart.loadingSpan = null;
  438. }, 250);
  439. }
  440. // Go back to prototype, ready to build
  441. delete series.buildKDTree;
  442. series.buildKDTree();
  443. // Don't do async on export, the exportChart, getSVGForExport and
  444. // getSVG methods are not chained for it.
  445. }, chart.renderer.forExport ? Number.MAX_VALUE : void 0);
  446. }
  447. });
  448. seriesTypes.scatter.prototype.cvsMarkerCircle = function (ctx, clientX, plotY, r) {
  449. ctx.moveTo(clientX, plotY);
  450. ctx.arc(clientX, plotY, r, 0, 2 * Math.PI, false);
  451. };
  452. // Rect is twice as fast as arc, should be used for small markers
  453. seriesTypes.scatter.prototype.cvsMarkerSquare = function (ctx, clientX, plotY, r) {
  454. ctx.rect(clientX - r, plotY - r, r * 2, r * 2);
  455. };
  456. seriesTypes.scatter.prototype.fill = true;
  457. if (seriesTypes.bubble) {
  458. seriesTypes.bubble.prototype.cvsMarkerCircle = function (ctx, clientX, plotY, r, i) {
  459. ctx.moveTo(clientX, plotY);
  460. ctx.arc(clientX, plotY, this.radii && this.radii[i], 0, 2 * Math.PI, false);
  461. };
  462. seriesTypes.bubble.prototype.cvsStrokeBatch = 1;
  463. }
  464. extend(seriesTypes.area.prototype, {
  465. cvsDrawPoint: function (ctx, clientX, plotY, yBottom, lastPoint) {
  466. if (lastPoint && clientX !== lastPoint.clientX) {
  467. ctx.moveTo(lastPoint.clientX, lastPoint.yBottom);
  468. ctx.lineTo(lastPoint.clientX, lastPoint.plotY);
  469. ctx.lineTo(clientX, plotY);
  470. ctx.lineTo(clientX, yBottom);
  471. }
  472. },
  473. fill: true,
  474. fillOpacity: true,
  475. sampling: true
  476. });
  477. extend(seriesTypes.column.prototype, {
  478. cvsDrawPoint: function (ctx, clientX, plotY, yBottom) {
  479. ctx.rect(clientX - 1, plotY, 1, yBottom - plotY);
  480. },
  481. fill: true,
  482. sampling: true
  483. });
  484. Chart.prototype.callbacks.push(function (chart) {
  485. /**
  486. * @private
  487. */
  488. function canvasToSVG() {
  489. if (chart.boostCopy) {
  490. chart.boostCopy();
  491. }
  492. }
  493. /**
  494. * @private
  495. */
  496. function clear() {
  497. if (chart.renderTarget) {
  498. chart.renderTarget.attr({ href: '' });
  499. }
  500. if (chart.canvas) {
  501. chart.canvas.getContext('2d').clearRect(0, 0, chart.canvas.width, chart.canvas.height);
  502. }
  503. }
  504. addEvent(chart, 'predraw', clear);
  505. addEvent(chart, 'render', canvasToSVG);
  506. });
  507. };
  508. export default initCanvasBoost;