Skip to content

Commit

Permalink
Example showing canvas->img rendering
Browse files Browse the repository at this point in the history
  • Loading branch information
zpao committed May 6, 2024
1 parent 0f6c240 commit f79b365
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
8 changes: 8 additions & 0 deletions examples/demo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {createRoot} from 'react-dom/client';
import {version} from '../package.json';
import {FullDemo} from './full';
import {DownloadDemo} from './download';
import {ImageDemo} from './image';

const DEMOS = {
full: {
Expand All @@ -18,6 +19,13 @@ const DEMOS = {
component: DownloadDemo,
file: 'examples/download.tsx',
},
image: {
label: '<img>',
description:
'Demo showing how to use refs to access the underlying canvas element and extract the image data to render an HTML <img>.',
component: ImageDemo,
file: 'examples/image.tsx',
},
};

type DemoComponentKeys = keyof typeof DEMOS;
Expand Down
44 changes: 44 additions & 0 deletions examples/image.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {QRCodeCanvas} from '..';
import React, {useEffect, useRef, useState} from 'react';

function ImageDemo() {
const canvasRef = useRef<HTMLCanvasElement>(null);
const [imgDataURL, setImgDataURL] = useState<string | undefined>(undefined);

useEffect(() => {
const node = canvasRef.current;
if (node == null) {
return;
}
const dataURI = node.toDataURL('image/png');
setImgDataURL(dataURI);
}, [canvasRef]);

return (
<>
<p>
Similar to the Download demo, this demo shows how you can use{' '}
<code>ref</code>s to access the underlying DOM nodes. In this case it
will be used to render a proper <code>&lt;img&gt;</code> element. This
is done by getting the raw image data from the rendered QRCodeCanvas.
</p>
<p>
While browsers typically treat canvas elements as images in most ways,
there are some advantages to img elements. For example, on in Mobile
Safari, long pressing on eSIM QR Codes in img elements enables a native
install method. This does not happen for canvas elements.
</p>

<div className="container">
<div>
<div style={{display: 'none'}}>
<QRCodeCanvas ref={canvasRef} value="hello world" size={256} />
</div>
<img src={imgDataURL} height={256} width={256} />
</div>
</div>
</>
);
}

export {ImageDemo};

0 comments on commit f79b365

Please sign in to comment.