本文介绍了模拟背景尺寸:画布中的封面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这样的画布上绘制图像:

I'm drawing images on a canvas like this:

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

图片被拉长了,我不想要这个.如何模拟 CSS 属性?

The picture is getting stretched and I don't want this. How can I simulate the CSS property?

background-size: cover

在画布上绘制图像时?

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

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

see the difference between 100% 100% (what I currently have) and cover (my goal).

推荐答案

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

It's a bit more complicated to get a cover functionality, though here is one solution for this:

更新 2016-04-03 以解决特殊情况.另请参阅下面@Yousef 的评论.

Updated 2016-04-03 to address special cases. Also see @Yousef's comment below.

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

现在你可以这样称呼它:

Now you can call it like this:

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

它会按比例缩放图像以适应该容器的内部.

and it will scale the image proportionally to fit inside in that container.

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

Use the two last parameters to offset the image:

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

希望这有帮助!

这篇关于模拟背景尺寸:画布中的封面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:32