index.js (2064B)
1 import { h, Component } from 'preact'; 2 import helpers from '../helpers'; 3 import consts from '../consts'; 4 import UpdateOnResize from '../UpdateOnResize/'; 5 import './style.css'; 6 7 const drawArea = helpers.soon((amplitudes, canvas, begin = 0, end = undefined) => { 8 const ctx = canvas.getContext("2d"); 9 const rectWidth = canvas.width / consts.BUF_SIZE; 10 const roundedWidth = Math.max(1, rectWidth) 11 const lineWidth = 1; 12 const halfCanvas = (canvas.height - lineWidth) / 2; 13 ctx.clearRect(0, 0, canvas.width, canvas.height); 14 ctx.beginPath(); 15 amplitudes.forEach((amp, idx) => { 16 amp *= halfCanvas; 17 const roundedXOffset = Math.round(idx * rectWidth); 18 ctx.rect(roundedXOffset, halfCanvas, roundedWidth + 1, -amp); 19 }); 20 ctx.fillStyle = "#ff735e"; 21 ctx.fill(); 22 ctx.closePath(); 23 }); 24 25 export default class WaveTable extends Component { 26 constructor() { 27 super(); 28 this.myDrawArea = helpers.throttle(() => { 29 drawArea(this.props.waveform, this.canvasRef); 30 }, 20, true); 31 } 32 33 componentDidMount() { 34 this.myDrawArea(this.props.waveform, this.canvasRef); 35 if (this.props.setCanvasRef) { 36 this.props.setCanvasRef(this.canvasRef); 37 } 38 } 39 40 componentDidUpdate() { 41 this.myDrawArea(); 42 } 43 44 render() { 45 const height = this.props.height || 400; 46 const width = this.props.width || document.getElementsByTagName('body')[0].clientWidth; 47 const pixelHeight = height * window.devicePixelRatio; 48 const pixelWidth = width * window.devicePixelRatio; 49 return ( 50 <UpdateOnResize action={this.forceUpdate.bind(this)}> 51 <canvas 52 class="wave-table" 53 style={`${this.props.myStyle}; height: ${height}px; width: ${width}px;`} 54 height={pixelHeight} 55 width={pixelWidth} 56 ref={(canvas) => {this.canvasRef = canvas}}> 57 </canvas> 58 </UpdateOnResize> 59 ); 60 } 61 }