Skip to content

Commit 99c2332

Browse files
fix(axis): scale tick labels to fix text truncation on chrome (#38)
fixes #18
1 parent 21867ca commit 99c2332

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

src/lib/axes/canvas_text_bbox_calculator.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,28 @@ export class CanvasTextBBoxCalculator implements BBoxCalculator {
55
private attachedRoot: HTMLElement;
66
private offscreenCanvas: HTMLCanvasElement;
77
private context: CanvasRenderingContext2D | null;
8-
// TODO specify styles for text
9-
// TODO specify how to hide the svg from the current dom view
10-
// like moving it a -9999999px
8+
private scaledFontSize: number;
9+
1110
constructor(rootElement?: HTMLElement) {
1211
this.offscreenCanvas = document.createElement('canvas');
1312
this.context = this.offscreenCanvas.getContext('2d');
1413
this.attachedRoot = rootElement || document.documentElement;
1514
this.attachedRoot.appendChild(this.offscreenCanvas);
15+
this.scaledFontSize = 100;
1616
}
1717
compute(text: string, fontSize = 16, fontFamily = 'Arial'): Option<BBox> {
1818
if (!this.context) {
1919
return none;
2020
}
21-
this.context.font = `${fontSize}px ${fontFamily}`;
21+
22+
// We scale the text up to get a more accurate computation of the width of the text
23+
// because `measureText` can vary a lot between browsers.
24+
const scalingFactor = this.scaledFontSize / fontSize;
25+
this.context.font = `${this.scaledFontSize}px ${fontFamily}`;
2226
const measure = this.context.measureText(text);
27+
2328
return some({
24-
width: measure.width,
29+
width: measure.width / scalingFactor,
2530
height: fontSize,
2631
});
2732
}

src/stories/axis.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from '..';
1616
import { PartialTheme } from '../lib/themes/theme';
1717
import { LineSeries } from '../specs';
18+
import { DataGenerator } from '../utils/data_generators/data_generator';
1819

1920
function createThemeAction(title: string, min: number, max: number, value: number) {
2021
return number(title, value, {
@@ -266,4 +267,28 @@ storiesOf('Axis', module)
266267
/>
267268
</Chart>
268269
);
270+
})
271+
.add('w many tick labels', () => {
272+
const dg = new DataGenerator();
273+
const data = dg.generateSimpleSeries(31);
274+
return (
275+
<Chart renderer="canvas" className={'story-chart'}>
276+
<Settings debug={true} />
277+
<Axis
278+
id={getAxisId('bottom')}
279+
position={Position.Bottom}
280+
title={'Bottom axis'}
281+
showOverlappingTicks={true}
282+
/>
283+
<AreaSeries
284+
id={getSpecId('lines')}
285+
xScaleType={ScaleType.Linear}
286+
yScaleType={ScaleType.Linear}
287+
xAccessor="x"
288+
yAccessors={['y']}
289+
data={data}
290+
yScaleToDataExtent={false}
291+
/>
292+
</Chart>
293+
);
269294
});

0 commit comments

Comments
 (0)