我正在这样的画布上绘制图像:
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
(我的目标)之间的区别。
获得封面功能要稍微复杂一些,尽管这里有一个解决方案:
更新了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);
希望这可以帮助!
我发现这是一个很好的起点,但是要注意许多与浮点精度有关的错误。例如,假设尺寸为728,比率为0.25686813186813184;结果为186.99999999999997,实际的画布宽度为187,因此检查高度/宽度是否小于宽度/高度将为true,因此宽高比在不应该更改的情况下会更改。我发现最好的方法是用parseInt和toFixed包装十进制数字,就像这样:parseInt(num.toFixed(8))。
好答案!我注意到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;
但不确定)这是否是最干净的解决方案在某些情况下,如果您使用的是已经在DOM中渲染的图像,则画布的结果可能不会完全模仿背景封面。要解决此问题,请使用
img.naturalWidth
和img.winHeight
代替img.width
和img.height
。您将确保该值基于原始图像的宽度和高度。(仅与IE8及更低版本不兼容)看起来“演示”页面不再可用
演示页面不可用,但是无论如何,您的代码对我有很大帮助。谢谢