Html5-canvas Tutorial => Scaling Image To Fit Or Fill.
Có thể bạn quan tâm
Example
Scaling to fit
Means that the whole image will be visible but there may be some empty space on the sides or top and bottom if the image is not the same aspect as the canvas. The example shows the image scaled to fit. The blue on the sides is due to the fact that the image is not the same aspect as the canvas.
Scaling to fill
Means that the image is scaled so that all the canvas pixels will be covered by the image. If the image aspect is not the same as the canvas then some parts of the image will be clipped. The example shows the image scaled to fill. Note how the top and bottom of the image are no longer visible.
Example Scale to fit
var image = new Image(); image.src = "imgURL"; image.onload = function(){ scaleToFit(this); } function scaleToFit(img){ // get the scale var scale = Math.min(canvas.width / img.width, canvas.height / img.height); // get the top left position of the image var x = (canvas.width / 2) - (img.width / 2) * scale; var y = (canvas.height / 2) - (img.height / 2) * scale; ctx.drawImage(img, x, y, img.width * scale, img.height * scale); }Example Scale to fill
var image = new Image(); image.src = "imgURL"; image.onload = function(){ scaleToFill(this); } function scaleToFill(img){ // get the scale var scale = Math.max(canvas.width / img.width, canvas.height / img.height); // get the top left position of the image var x = (canvas.width / 2) - (img.width / 2) * scale; var y = (canvas.height / 2) - (img.height / 2) * scale; ctx.drawImage(img, x, y, img.width * scale, img.height * scale); }The only differance between the two functions is getting the scale. The fit uses the min fitting scale will the fill uses the max fitting scale.
Got any html5-canvas Question?
Ask any html5-canvas Questions and Get Instant Answers from ChatGPT AI: ChatGPT answer me! PDF - Download html5-canvas for free Previous NextTừ khóa » Html Canvas Stretch Image
-
Html5 Canvas DrawImage Stretched - Javascript - Stack Overflow
-
HTML Canvas DrawImage() Method - W3Schools
-
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 Resize Image With JavaScript Canvas? - The Web Dev
-
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