diff --git a/src/lib/axes/canvas_text_bbox_calculator.ts b/src/lib/axes/canvas_text_bbox_calculator.ts index ccc45e3bc8..ba1f0ee289 100644 --- a/src/lib/axes/canvas_text_bbox_calculator.ts +++ b/src/lib/axes/canvas_text_bbox_calculator.ts @@ -5,23 +5,28 @@ export class CanvasTextBBoxCalculator implements BBoxCalculator { private attachedRoot: HTMLElement; private offscreenCanvas: HTMLCanvasElement; private context: CanvasRenderingContext2D | null; - // TODO specify styles for text - // TODO specify how to hide the svg from the current dom view - // like moving it a -9999999px + private scaledFontSize: number; + constructor(rootElement?: HTMLElement) { this.offscreenCanvas = document.createElement('canvas'); this.context = this.offscreenCanvas.getContext('2d'); this.attachedRoot = rootElement || document.documentElement; this.attachedRoot.appendChild(this.offscreenCanvas); + this.scaledFontSize = 100; } compute(text: string, fontSize = 16, fontFamily = 'Arial'): Option { if (!this.context) { return none; } - this.context.font = `${fontSize}px ${fontFamily}`; + + // We scale the text up to get a more accurate computation of the width of the text + // because `measureText` can vary a lot between browsers. + const scalingFactor = this.scaledFontSize / fontSize; + this.context.font = `${this.scaledFontSize}px ${fontFamily}`; const measure = this.context.measureText(text); + return some({ - width: measure.width, + width: measure.width / scalingFactor, height: fontSize, }); } diff --git a/src/stories/axis.tsx b/src/stories/axis.tsx index 62c88b3eff..7b238fcfb2 100644 --- a/src/stories/axis.tsx +++ b/src/stories/axis.tsx @@ -15,6 +15,7 @@ import { } from '..'; import { PartialTheme } from '../lib/themes/theme'; import { LineSeries } from '../specs'; +import { DataGenerator } from '../utils/data_generators/data_generator'; function createThemeAction(title: string, min: number, max: number, value: number) { return number(title, value, { @@ -266,4 +267,28 @@ storiesOf('Axis', module) /> ); + }) + .add('w many tick labels', () => { + const dg = new DataGenerator(); + const data = dg.generateSimpleSeries(31); + return ( + + + + + + ); });