No high-level set-up here. All we need, are just two files.
app.js. (Name it whatever you want). Open
index.html file and link
app.js to it. Also, add elements in the
index.html file like this.
First off, select the canvas element using DOM Selector.
const canvas = document.querySelectorAll('canvas');
querySelectorAll() because we have two canvas elements in out index file. Also, add CSS according to this CSS file.
I learnt a lot of new things related to the canvas while building this simple app. They are:
ImageData Object etc. I will try my best to explain each one of them :)
How to copy a part from a canvas
2d context exposes a method,
getImageData(), which accepts a few arguments. They are:
y: the x-axis and y-axis from where it should start copying the image.
height: it is the dimension of the image to be copied.
For example, if we put
ctx.getImageData(10, 10, 300, 300), we will get an image of 300px by 300px from x = 10 and y = 10.
ImageData in another canvas
To load the copied image in another canvas, we have
putImageData() method. This method also accepts a few arguments.
ImageData: An object. This parameter should contain the image data, i.e.
widthand an array which represents the image pixels.
y: the x-axis and y-axis from where it should start putting the copied image
width: the height and width of the image to be drawn.
Have a Great Day Ahead!