How To Resize Image With JavaScript Canvas? - The Web Dev
Có thể bạn quan tâm
Sometimes, we want to resize image with JavaScript canvas.
In this article, we’ll look at how to resize image with JavaScript canvas.
How to resize image with JavaScript canvas?
To resize image with JavaScript canvas, we call drawImage with the given image width and height.
For instance, we write
const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); const img = new Image(); img.onload = () => { canvas.height = canvas.width * (img.height / img.width); const oc = document.createElement("canvas"); const octx = oc.getContext("2d"); oc.width = img.width * 0.5; oc.height = img.height * 0.5; octx.drawImage(img, 0, 0, oc.width, oc.height); octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5); ctx.drawImage( oc, 0, 0, oc.width * 0.5, oc.height * 0.5, 0, 0, canvas.width, canvas.height ); }; img.src = "https://picsum.photos/200/300";to set the img.onload property to a function that runs when the image is loaded.
In it, we set the canvas height and width with
canvas.height = canvas.width * (img.height / img.width);We resize the the image to 50% of its original size with
const oc = document.createElement("canvas"); const octx = oc.getContext("2d"); oc.width = img.width * 0.5; oc.height = img.height * 0.5; octx.drawImage(img, 0, 0, oc.width, oc.height);Then we resize it to its final size with
ctx.drawImage( oc, 0, 0, oc.width * 0.5, oc.height * 0.5, 0, 0, canvas.width, canvas.height );We draw the resized image by drawing the image in the oc canvas width 50% of the size of the oc canvas.
Conclusion
To resize image with JavaScript canvas, we call drawImage with the given image width and height.
Từ khóa » Html Canvas Stretch Image
-
Html5 Canvas DrawImage Stretched - Javascript - Stack Overflow
-
HTML Canvas DrawImage() Method - W3Schools
-
Html5-canvas Tutorial => Scaling Image To Fit Or Fill.
-
Resize Image Using HTML Canvas In JavaScript | Delft Stack
-
Resize Image To Fixed Size - Canvas, Images And Pixels
-
HTML5 Resize Image In Canvas
-
How To Resize An Image In An HTML 5 Canvas ? - GeeksforGeeks
-
Javascript – HTML Canvas: Scaling Image To Fit Without Stretching
-
CanvasRenderingContext2D.drawImage() - Web APIs | MDN
-
ageSmoothingEnabled - Web APIs
-
How To Scale An Image To Fit On Canvas With JavaScript?
-
Resize Images In JavaScript The Right Way
-
Stretch Image Inside Canvas - ADocLib
-
HTML Canvas - DrawImage - Stretched Results - Ars Technica