Home >Web Front-end >CSS Tutorial >How to Simulate CSS `background-size: cover` in Canvas?
Simulating CSS Background-Size: Cover in Canvas
Canvas drawing involves rendering images on a 2D context. However, when drawing images using the drawImage() method, it's possible to encounter issues with image stretching or distortion. This can be addressed by simulating the CSS property background-size: cover, which scales the image while preserving its aspect ratio to fit within the desired dimensions.
One method to achieve this behavior in canvas is through the following function:
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) { // Default arguments and validation if (arguments.length === 2) { x = y = 0; w = ctx.canvas.width; h = ctx.canvas.height; } offsetX = typeof offsetX === "number" ? offsetX : 0.5; offsetY = typeof offsetY === "number" ? offsetY : 0.5; // Image dimensions and aspect ratio var iw = img.width, ih = img.height, r = Math.min(w / iw, h / ih), nw = iw * r, // New proposed width nh = ih * r, // New proposed height cx, cy, cw, ch, ar = 1; // Determine image scaling factor if (nw < w) ar = w / nw; if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh; // Updated nw *= ar; nh *= ar; // Calculate source rectangle cw = iw / (nw / w); ch = ih / (nh / h); cx = (iw - cw) * offsetX; cy = (ih - ch) * offsetY; // Validate source rectangle if (cx < 0) cx = 0; if (cy < 0) cy = 0; if (cw > iw) cw = iw; if (ch > ih) ch = ih; // Draw the image to the destination rectangle ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h); }
This function can be invoked as follows:
drawImageProp(ctx, image, 0, 0, width, height);
This will scale the image proportionally to fit within the provided width and height dimensions. The optional offsetX and offsetY parameters allow for image offsetting within the destination rectangle.
The above is the detailed content of How to Simulate CSS `background-size: cover` in Canvas?. For more information, please follow other related articles on the PHP Chinese website!