I have a very specific question regarding Three Fiber. When you click on download, it creates a base64 using toDataURL which you can then download. The image has the height and width of the canvas and the canvas has the height and width of the browser window. If the browser window is 1024x768 the image has the same size. Is it possible that no matter what the height and width of the canvas is, that the image has the height and width of 1920x1080 pixels? I have no idea how to implement this.
export default function Home() {
const canvas = useRef()
const [downloadDatei, setDownloadDatei] = useState('')
const downloadCanvas = () => {
const download = canvas.current.toDataURL('image/jpeg', );
setDownloadDatei(download)
}
return (
<div className="mitte">
<section className="canvasSection">
<Canvas
ref={canvas}
className="canvas"
shadows
linear
camera={{ position: [10, 0, 80], fov: 45 }}
>
<Suspense fallback={false}>
<Content />
</Suspense>
</Canvas>
</section>
<button >
<a href={downloadDatei} download='test.jpg' onClick={() => downloadCanvas()}>
Download
</a>
</button>
</div>
)
}
The .toDataUrl() method of a HTMLCanvasElement object returns the canvas as it is thus you can not directly change it's size.
What you can do instead is drawing the contents of your canvas to a temporary <canvas> element the size of your desired resolution e.g. 1920x1080.
Afterwards execute .toDataUrl on the temporary canvas.
Here's an example:
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.lineWidth = 10;
ctx.arc(canvas.width / 2, canvas.height / 2, 50, 0, 2 * Math.PI);
ctx.stroke();
function downloadCanvas() {
let tempCanvas = document.createElement("canvas");
tempCanvas.width = 1920;
tempCanvas.height = 1080;
let tempContext = tempCanvas.getContext("2d");
tempContext.drawImage(canvas, 0, 0, tempCanvas.width, tempCanvas.height)
const download = tempCanvas.toDataURL('image/jpeg');
document.querySelectorAll("a")[0].href = download;
}
<canvas id="canvas" width="320" height="180"></canvas><br>
<a href="" download='test.jpg' onClick=" downloadCanvas()">Download</a>