BoostCanvas.js 22 KB

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