JSFiddle - React, Tailwind, and code Playground
by kassiomaia
HTML
<div id="root" />
CSS
:root {
--bg-color: #403434;
}
body, div {
margin: 0;
padding: 0;
}
.application {
background: var(--bg-color);
width: 100vw;
height: 100vh;
}
React
const { useState, useEffect, createRef } = React
function Canvas({ width, height }) {
return (
<canvas width={width} height={height} />
)
}
const CanvasManager = (function(width, height) {
let GlobalContext;
const Updater = {
handle(timestamp) {
requestAnimationFrame(this.handle)
}
}
Updater.handle = Updater.handle.bind(Updater)
function Canvas() {
return (
<canvas ref={(ref) => {
if (ref) {
GlobalContext = ref.getContext('2d')
}
}} width={width} height={height} />
)
}
requestAnimationFrame(Updater.handle)
return {
Canvas
}
})
function Application(props) {
const [[width, height], setDimenssions] = useState([0, 0])
const ref = createRef()
useEffect(() => {
if (ref.current) {
const { width, height } = ref.current.getClientRects()[0]
setDimenssions([width, height])
}
}, [width, height, setDimenssions])
const { Canvas } = CanvasManager(width, height)
return (
<div ref={ref} className="application">
<Canvas />
</div>
)
}
ReactDOM.render(<Application />, document.getElementById('root'))