stories/atoms/components/canvas/Canvas.stories.mdx

Summary

Maintainability
Test Coverage
import { ArgsTable, Meta, Story, Canvas, Preview, Props } from '@storybook/addon-docs'
import { Canvas as CanvasComponent } from 'ui/atoms/canvas/Canvas'
import { useElementSize } from 'hook/useElementSize'
import { drawStarField } from './starfield'
import { drawBouncingText } from './bouncingText'

<Meta
  title="Atoms/Canvas"
  component={CanvasComponent}
  parameters={{ actions: { argTypesRegex: '^on.*' } }}
/>

# Canvas

> A simple [canvas](https://www.w3schools.com/html/html5_canvas.asp) React component.

[![stability-unstable](https://img.shields.io/badge/stability-unstable-yellow.svg)](https://github.com/emersion/stability-badges#unstable)

## Overview

### Description

The `Canvas` component offers a seamless integration of the regular [canvas](https://www.w3schools.com/html/html5_canvas.asp) HTML element in React, so we can
just draw inside it like we usually do on the fly, via JavaScript.

---

export const SimpleCanvas = args => {
  const [ size, divRef ] = useElementSize()
  const ratio = 21/9
  const [ w, h ] = [size?.width, size?.width / ratio]
  return (
    <div style={{ textAlign: 'center' }} ref={divRef}>
      <CanvasComponent width={w} height={h} {...args} />
    </div>)
}

<Canvas>
  <Story
    name="Overview"
    args={{
      onRender: drawStarField(100),
      disableScrolling: false
    }}
  >
    {SimpleCanvas.bind({})}
  </Story>
</Canvas>

### Properties

<ArgsTable story="Overview" />

## Auto resize

Sometimes, you may want to resize the `Canvas` component to fit the element or window that it’s in. To do this, simply bind the `resize` event and, once the event is caught,
resize the canvas by setting on the fly its `width` and `height` properties.

The OKP4 design system provides a simple mechanism for this: the hook `useElementSize`. This hook helps you to dynamically retrieve the width and the height of an HTML element.

For instance:

```tsx
const draw = (canvas, deltaCount) => { ... }
const [ size, divRef ] = useElementSize()

return (
<div style={{ textAlign: 'center', padding: '10px 0 10px' }} ref={divRef}>
  <CanvasComponent 
    width={size?.width} 
    height={size?.height} 
    onRender={draw} />
</div>)
```

export const ResizableCanvas = args => {
  const [ size, divRef ] = useElementSize()
  return (
    <div style={{ textAlign: 'center', padding: '10px 0 10px' }} ref={divRef}>
      <CanvasComponent width={size?.width} height={200} {...args} />
    </div>)
}

<Canvas>
  <Story
    name="Auto resize"
    args={{
      onRender: drawBouncingText,
      disableScrolling: false
    }}
  >
    {ResizableCanvas.bind({})}
  </Story>
</Canvas>