Home >Web Front-end >CSS Tutorial >How to Simulate CSS's `background-size: cover` in Canvas?

How to Simulate CSS's `background-size: cover` in Canvas?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 08:57:11583browse

How to Simulate CSS's `background-size: cover` in Canvas?

Simulating CSS's "background-size: cover" in Canvas

When drawing images on a canvas, you may encounter the issue of images being stretched. To achieve the desired "cover" functionality, which scales images proportionally to fit within a given container, a more complex approach is required.

One solution is the following JavaScript function:

/**
 * By Ken Fyrstenberg Nilsen
 *
 * drawImageProp(context, image [, x, y, width, height [,offsetX, offsetY]])
 *
 * If image and context are only arguments rectangle will equal canvas
 */
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {

    if (arguments.length === 2) {
        x = y = 0;
        w = ctx.canvas.width;
        h = ctx.canvas.height;
    }

    // default offset is center
    offsetX = typeof offsetX === "number" ? offsetX : 0.5;
    offsetY = typeof offsetY === "number" ? offsetY : 0.5;

    // keep bounds [0.0, 1.0]
    if (offsetX < 0) offsetX = 0;
    if (offsetY < 0) offsetY = 0;
    if (offsetX > 1) offsetX = 1;
    if (offsetY > 1) offsetY = 1;

    var iw = img.width,
        ih = img.height,
        r = Math.min(w / iw, h / ih),
        nw = iw * r,   // new prop. width
        nh = ih * r,   // new prop. height
        cx, cy, cw, ch, ar = 1;

    // decide which gap to fill
    if (nw < w) ar = w / nw;
    if (Math.abs(ar - 1) < 1e-14 &amp;&amp; nh < h) ar = h / nh;  // updated
    nw *= ar;
    nh *= ar;

    // calc source rectangle
    cw = iw / (nw / w);
    ch = ih / (nh / h);

    cx = (iw - cw) * offsetX;
    cy = (ih - ch) * offsetY;

    // make sure source rectangle is valid
    if (cx < 0) cx = 0;
    if (cy < 0) cy = 0;
    if (cw > iw) cw = iw;
    if (ch > ih) ch = ih;

    // fill image in dest. rectangle
    ctx.drawImage(img, cx, cy, cw, ch,  x, y, w, h);
}

To use this function:

  1. Call drawImageProp(ctx, image, 0, 0, width, height); to scale the image proportionally to fit inside the container.
  2. To offset the image, use the last two parameters: drawImageProp(ctx, image, 0, 0, width, height, offsetX, offsetY);. Offsets range from 0.0 (left/top) to 1.0 (right/bottom).

The above is the detailed content of How to Simulate CSS's `background-size: cover` in Canvas?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn