To shrink the size of an image in vanilla JavaScript, you can use the HTML canvas element. The steps are as follows:
Image
object and set its src
attribute to the URL of the image you want to shrink.index.tsx54 chars3 lines
canvas
element and its context (2D
), then set the dimensions of the canvas to the desired smaller size.index.tsx185 chars6 lines
drawImage
method, specifying the original Image
object and the dimensions of the new shrunk image.index.tsx86 chars2 lines
toDataURL()
method, which encodes the image as a base64 data string, as shown below.index.tsx100 chars3 lines
The final code would look like this:
index.tsx428 chars14 lines
gistlibby LogSnag