Подтвердить что ты не робот

Моделирование фонового размера: обложка в холсте

Я рисую изображения на холст следующим образом:

ctx.drawImage(data[i].image, data[i].pos.x, data[i].pos.y, data[i].pos.w, data[i].pos.h);

Дело в том, что картина растягивается, и я не хочу этого. Как я могу имитировать свойство css

background-size: cover

при рисовании изображения в кавах.

http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=cover

см. разницу между 100% 100% (что у меня есть) и cover (моя цель).

4b9b3361

Ответ 1

Немного сложнее получить функциональность обложки, хотя здесь есть одно решение для этого:

Демо

Обновлено 2016-04-03 для решения особых случаев. Также см. Комментарий @Yousef ниже.

/**
 * 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 && 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);
}

Теперь вы можете вызвать его так:

drawImageProp(ctx, image, 0, 0, width, height);

и он будет масштабировать изображение пропорционально, чтобы поместиться внутри этого контейнера.

Используйте два последних параметра для смещения изображения:

var offsetX = 0.5;   // center x
var offsetY = 0.5;   // center y
drawImageProp(ctx, image, 0, 0, width, height, offsetX, offsetY);

Надеюсь, это поможет!

Ответ 2

Если вы ищете более простое решение, которое будет работать в большинстве случаев, а также включает функцию css contain, попробуйте следующее:

function fit(contains) {
  return (parentWidth, parentHeight, childWidth, childHeight, scale = 1, offsetX = 0.5, offsetY = 0.5) => {
    const childRatio = childWidth / childHeight
    const parentRatio = parentWidth / parentHeight
    let width = parentWidth * scale
    let height = parentHeight * scale

    if (contains ? (childRatio > parentRatio) : (childRatio < parentRatio)) {
      height = width / childRatio
    } else {
      width = height * childRatio
    }

    return {
      width,
      height,
      offsetX: (parentWidth - width) * offsetX,
      offsetY: (parentHeight - height) * offsetY
    }
  }
}

export const contain = fit(true)
export const cover = fit(false)

слегка измененная версия intrinsic-scale, чтобы включить масштаб и смещение

Использование:

import {cover, contain} from './intrinsic-scale'

const {
  offsetX, 
  offsetY, 
  width, 
  height
} = cover(parentWidth, parentHeight, imageWidth, imageHeight)

// or...

const {
  offsetX, 
  offsetY, 
  width, 
  height
} = contain(parentWidth, parentHeight, imageWidth, imageHeight)

ctx.drawImage(image, offsetX, offsetY, width, height)