boost-canvas.src.js 22 KB

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