Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/rosszurowski/react-responsive-canvas
Fit a canvas element to its parent
https://github.com/rosszurowski/react-responsive-canvas
canvas react responsive
Last synced: 1 day ago
JSON representation
Fit a canvas element to its parent
- Host: GitHub
- URL: https://github.com/rosszurowski/react-responsive-canvas
- Owner: rosszurowski
- License: mit
- Created: 2018-08-06T06:18:45.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2018-08-30T17:04:53.000Z (over 6 years ago)
- Last Synced: 2024-12-25T16:51:36.587Z (4 days ago)
- Topics: canvas, react, responsive
- Language: JavaScript
- Homepage:
- Size: 24.4 KB
- Stars: 13
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# react-responsive-canvas
[![npm](https://badgen.now.sh/npm/v/react-responsive-canvas)](https://www.npmjs.com/package/react-responsive-canvas)
Simple React component for a canvas that fits the size of its parent.
## Installation
```
npm install --save react-responsive-canvas
```## Usage
#### Props
* `canvasRef: (el: HTMLCanvasElement) => void` - A [ref callback function](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) to set a reference to the `canvas` element
* `onResize: () => void` - A callback for when the canvas resizes
* `scale: number` - A ratio to scale the canvas by. Used to support high-quality canvases on retina screens. Defaults to `window.devicePixelRatio`#### Example
```jsx
import Canvas from 'react-responsive-canvas';class App extends Component {
componentDidMount() {
this.ctx = this.canvas.getContext('2d');
this.draw();
}draw() {
// Draw whatever
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
}render () {
return (
(this.canvas = el)}
onResize={this.draw} />
);
}
}
```## Context
By default, HTML `` elements are a fixed size. When creating animated canvas graphics, I usually want the canvas to take the shape of the container it sits in — whether that's the whole page, or a header image.
After writing this component too many times using [hughsk/canvas-fit](https://github.com/hughsk/canvas-fit), I built this module.
It auto-resizes the canvas to fill it's container, and by default scales the canvas to match the user's screen resolution (ie. regular vs. retina screens).
## License
MIT