模拟背景大小:在画布上覆盖

Dee*_*psy 35 html javascript css html5 canvas

我正在画像这样的画布:

ctx.drawImage(data[i].image, data[i].pos.x, data[i].pos.y, data[i].pos.w, data[i].pos.h);
Run Code Online (Sandbox Code Playgroud)

问题是图片越来越拉伸,我不希望这样.我如何模拟css属性

background-size: cover
Run Code Online (Sandbox Code Playgroud)

在卡瓦斯画图像.

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

看看100% 100%(我现在拥有的)和cover(我的目标)之间的区别.

小智 83

获得封面功能有点复杂,虽然这里有一个解决方案:

演示

更新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);
}
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样调用它:

drawImageProp(ctx, image, 0, 0, width, height);
Run Code Online (Sandbox Code Playgroud)

它将按比例缩放图像以适合该容器内部.

使用最后两个参数来偏移图像:

var offsetX = 0.5;   // center x
var offsetY = 0.5;   // center y
drawImageProp(ctx, image, 0, 0, width, height, offsetX, offsetY);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 很棒的答案!我注意到JS中的浮点可能存在一些问题.例如,img.width = 225,img.height = 400,w = 58,h = 58.在Chrome中,它会调整到错误的尺寸.我通过改变来解决这个问题:`if(nw <w)ar = w/nw; if(nh <h)ar = h/nh;`变为`if(Math.round(nw)<w)ar = w/nw; if(Math.round(nh)<h)ar = h/nh;`但不确定这是否是最干净的解决方案 (2认同)
  • 在某些情况下,如果您使用的是已在DOM中渲染的图像,则画布的结果可能不会完全模仿背景封面。为了解决这个问题,请使用img.naturalWidth和img.winHeight而不是img.width和img.height。您将确保该值基于原始图像的宽度和高度。(仅与IE8及更低版本不兼容) (2认同)

小智 9

画布图像适合画布,如背景大小的封面和包含

const coverImg = (img, type) => {
  const imgRatio = img.height / img.width
  const winRatio = window.innerHeight / window.innerWidth
  if ((imgRatio < winRatio && type === 'contain') || (imgRatio > winRatio && type === 'cover')) {
    const h = window.innerWidth * imgRatio
    ctx.drawImage(img, 0, (window.innerHeight - h) / 2, window.innerWidth, h)
  }
  if ((imgRatio > winRatio && type === 'contain') || (imgRatio < winRatio && type === 'cover')) {
    const w = window.innerWidth * winRatio / imgRatio
    ctx.drawImage(img, (win.w - w) / 2, 0, w, window.innerHeight)
  }
}
Run Code Online (Sandbox Code Playgroud)

Codepen 演示

用法:

coverImg(myImage, 'cover');
coverImg(myImage, 'contain');
Run Code Online (Sandbox Code Playgroud)


dav*_*tar 7

如果您正在寻找一种适用于大多数情况的简单解决方案,并且还包括类似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)
Run Code Online (Sandbox Code Playgroud)

内在尺度的略微修改版本,包括尺度和偏移

用法:

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)
Run Code Online (Sandbox Code Playgroud)