Skip to content

Commit

Permalink
fix(axis): scale tick labels to fix text truncation on chrome (opense…
Browse files Browse the repository at this point in the history
  • Loading branch information
emmacunningham authored Feb 6, 2019
1 parent a18400c commit 3e6a400
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
15 changes: 10 additions & 5 deletions packages/osd-charts/src/lib/axes/canvas_text_bbox_calculator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<BBox> {
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,
});
}
Expand Down
25 changes: 25 additions & 0 deletions packages/osd-charts/src/stories/axis.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -266,4 +267,28 @@ storiesOf('Axis', module)
/>
</Chart>
);
})
.add('w many tick labels', () => {
const dg = new DataGenerator();
const data = dg.generateSimpleSeries(31);
return (
<Chart renderer="canvas" className={'story-chart'}>
<Settings debug={true} />
<Axis
id={getAxisId('bottom')}
position={Position.Bottom}
title={'Bottom axis'}
showOverlappingTicks={true}
/>
<AreaSeries
id={getSpecId('lines')}
xScaleType={ScaleType.Linear}
yScaleType={ScaleType.Linear}
xAccessor="x"
yAccessors={['y']}
data={data}
yScaleToDataExtent={false}
/>
</Chart>
);
});

0 comments on commit 3e6a400

Please sign in to comment.