BoostCanvas.js 22 KB

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