Last active
October 8, 2018 00:19
-
-
Save spion/a37c256d7bde0763949d824a56b58475 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface MobxCanvasProps { | |
width?: number; | |
height?: number; | |
style?: any; | |
render(ctx: CanvasRenderingContext2D): void; | |
} | |
@observer | |
export class MobxCanvas extends React.Component<CanvasProps> { | |
private canvasRef = React.createRef(); | |
private stopAutorun: IReactionDisposer = null!; | |
private ctx: CanvasRenderingContext2D | null = null; | |
private currentRef: HTMLCanvasElement | null = null; | |
private renderAutorun = () => { | |
if (!this.currentRef) { | |
this.currentRef = this.canvasRef.current as HTMLCanvasElement; | |
this.ctx = null; | |
} | |
if (!this.ctx && this.currentRef) this.ctx = this.currentRef.getContext('2d'); | |
if (this.ctx) this.props.render(this.ctx); | |
}; | |
componentDidMount() { | |
this.stopAutorun = autorun(this.renderAutorun); | |
} | |
componentWillUnmount() { | |
this.stopAutorun && this.stopAutorun(); | |
} | |
render() { | |
return ( | |
<canvas width={this.props.width} height={this.props.height} ref={this.canvasRef as any} /> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<MobxCanvas width={this.canvasWidth} height={this.canvasHeight} render={(ctx: CanvasRenderingContext2D) => { | |
let fs = this.fa.frequencies; | |
let ms = this.fa.magnitudes; | |
ctx.clearRect(0, 0, 1000, 1000); | |
ctx.strokeStyle = '#999' | |
ctx.beginPath() | |
for (var k = 0; k <= 32; k += 2) { | |
let y = this.canvasHeight * k / 32; | |
ctx.moveTo(0, y); | |
ctx.lineTo(this.canvasWidth, y); | |
} | |
for (let freq of freqs) { | |
let x = logScale(freq, 0, this.canvasWidth) | |
ctx.moveTo(x, 0) | |
ctx.lineTo(x, this.canvasHeight); | |
} | |
ctx.stroke() | |
ctx.strokeStyle = '#000' | |
let first = this.freqMagToXY(fs[0], ms[0]); | |
ctx.beginPath(); | |
ctx.moveTo(first.x, first.y); | |
for (let k = 1; k < fs.length; ++k) { | |
let pt = this.freqMagToXY(fs[k], ms[k]); | |
ctx.lineTo(pt.x, pt.y); | |
} | |
ctx.stroke(); | |
}} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment