Bez popisu

Canvas.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //@flow
  2. import React, { useRef, useState, useEffect, useCallback } from 'react';
  3. import { SafeAreaView, Image } from 'react-native';
  4. import ViewShot from 'react-native-view-shot';
  5. import Canvas from 'react-native-canvas';
  6. const dimension = { width: 300, height: 300 };
  7. const CanvasRendering = ({ onDrawn }) => {
  8. const ref = useRef();
  9. useEffect(() => {
  10. const ctx = ref.current.getContext('2d');
  11. ctx.fillStyle = '#eee';
  12. ctx.fillRect(0, 0, ref.current.width, ref.current.height);
  13. ctx.fillStyle = 'red';
  14. ctx.fillRect(120, 30, 60, 60);
  15. ctx.fillStyle = 'blue';
  16. ctx.fillRect(140, 50, 60, 60);
  17. const timeout = setTimeout(onDrawn, 1000); // hack. react-native-canvas have no way to tell when it's executed
  18. return () => clearTimeout(timeout);
  19. }, [onDrawn]);
  20. return <Canvas ref={ref} style={dimension} />;
  21. };
  22. const CanvasExample = () => {
  23. const [source, setSource] = useState(null);
  24. const viewShotRef = useRef();
  25. const onCapture = useCallback(() => {
  26. viewShotRef.current.capture().then(uri => setSource({ uri }));
  27. }, []);
  28. return (
  29. <SafeAreaView>
  30. <ViewShot ref={viewShotRef} style={dimension}>
  31. <CanvasRendering onDrawn={onCapture} />
  32. </ViewShot>
  33. <Image fadeDuration={0} source={source} style={dimension} />
  34. </SafeAreaView>
  35. );
  36. };
  37. CanvasExample.navigationOptions = {
  38. title: 'react-native-canvas',
  39. };
  40. export default CanvasExample;