Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow resizing the canvas #177

Open
FredrikMeyer opened this issue May 26, 2023 · 0 comments
Open

Allow resizing the canvas #177

FredrikMeyer opened this issue May 26, 2023 · 0 comments

Comments

@FredrikMeyer
Copy link
Owner

Some ideas from ChatGPT

import React, { useRef, useEffect } from 'react';
import ResizeObserver from 'resize-observer-polyfill';

function MyComponent() {
  const ref = useRef(null);

  useEffect(() => {
    const element = ref.current;

    // Create a new ResizeObserver instance
    const resizeObserver = new ResizeObserver(entries => {
      // Iterate over the entries and handle size changes
      entries.forEach(entry => {
        console.log('Size changed:', entry.contentRect.width, entry.contentRect.height);
        // Perform any actions you want when size changes
      });
    });

    // Start observing the target element
    resizeObserver.observe(element);

    // Clean up the observer when the component is unmounted
    return () => {
      resizeObserver.unobserve(element);
      resizeObserver.disconnect();
    };
  }, []);

  return <div ref={ref}>Resizable Component</div>;
}

And:

function resizeCanvas(canvas, newWidth, newHeight) {
  // Create a new canvas element
  const newCanvas = document.createElement('canvas');
  
  // Set the new canvas dimensions
  newCanvas.width = newWidth;
  newCanvas.height = newHeight;
  
  // Get the 2D rendering context of the new canvas
  const context = newCanvas.getContext('2d');
  
  // Copy the content from the original canvas to the new canvas
  context.drawImage(canvas, 0, 0, newWidth, newHeight);
  
  // Replace the original canvas with the new canvas
  canvas.parentNode.replaceChild(newCanvas, canvas);
}

// Example usage
const originalCanvas = document.getElementById('myCanvas');
resizeCanvas(originalCanvas, 800, 600);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant