boost-canvas.src.js 25 KB

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