I have a large canvas element which I want to clone and display inside a new smaller canvas element to serve as a miniature display after the webpage is loaded.
I've created the new smaller blank canvas element ahead of time and have appended it to the DOM with a specific height/width.
The idea was to clone the large canvas element into the smaller one after the page is loaded using:
//grab the context from your destination canvas
const destCtx = destinationCanvas.getContext('2d');
//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);
However, all that is being displayed is a solid black background. My expectation is that the smaller canvas should now display a duplicate design of the larger canvas, just in a smaller sized area.
I've looked around a bit, but have not found a working solution to the issue as of yet.
A little sketch of what i'm trying to do:

Also tried the following:
const smallCanvas = document.getElementById('smallCanvas');
const bigCanvas = document.getElementById('bigCanvas');
smallCanvas.getContext('2d').drawImage(bigCanvas, 0, 0, bigCanvas.width, bigCanvas.height, 0, 0, smallCanvas.width, smallCanvas.height);
The result always looks like this:

This happens because you didn't pass any parameters to the drawImage() method except for the source and the position. In this case it will draw the image 1:1 onto the smaller canvas - which means you just see a fraction of your source canvas up to the dimensions of the small canvas.
To fix this you need to specify two rectangles (x, y, width, height) - the first being the values from the bigger and the second from the smaller.
e.g. drawImage(source,sourceX,sourceY,sourceWidth,sourceHeight,targetX,targetY,targetWidth,targetHeight);
Here's an example:
var bigCanvas = document.getElementById("bigCanvas");
var smallCanvas = document.getElementById("smallCanvas");
var img = new Image();
img.onload = function() {
bigCanvas.getContext('2d').drawImage(this, 0, 0);
smallCanvas.getContext('2d').drawImage(bigCanvas, 0, 0, bigCanvas.width, bigCanvas.height, 0, 0, smallCanvas.width, smallCanvas.height);
}
img.src = "https://picsum.photos/id/16/400/300";
<canvas id="bigCanvas" width="400" height="300"></canvas>
<canvas id="smallCanvas" width="40" height="30"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With