BoostCanvas.js 22 KB

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