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

我正在画像这样的画布:


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(我的目标)之间的区别。


大话西游666
浏览 572回答 2
2回答

慕莱坞森

如果您正在寻找一种适用于大多数情况的简单解决方案,并且还包括类似CSS contain的功能,请尝试以下方法:function fit(contains) {&nbsp; return (parentWidth, parentHeight, childWidth, childHeight, scale = 1, offsetX = 0.5, offsetY = 0.5) => {&nbsp; &nbsp; const childRatio = childWidth / childHeight&nbsp; &nbsp; const parentRatio = parentWidth / parentHeight&nbsp; &nbsp; let width = parentWidth * scale&nbsp; &nbsp; let height = parentHeight * scale&nbsp; &nbsp; if (contains ? (childRatio > parentRatio) : (childRatio < parentRatio)) {&nbsp; &nbsp; &nbsp; height = width / childRatio&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; width = height * childRatio&nbsp; &nbsp; }&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; width,&nbsp; &nbsp; &nbsp; height,&nbsp; &nbsp; &nbsp; offsetX: (parentWidth - width) * offsetX,&nbsp; &nbsp; &nbsp; offsetY: (parentHeight - height) * offsetY&nbsp; &nbsp; }&nbsp; }}export const contain = fit(true)export const cover = fit(false)内部比例的略微修改版本,包括比例和偏移用法:import {cover, contain} from './intrinsic-scale'const {&nbsp; offsetX,&nbsp;&nbsp; offsetY,&nbsp;&nbsp; width,&nbsp;&nbsp; height} = cover(parentWidth, parentHeight, imageWidth, imageHeight)// or...const {&nbsp; offsetX,&nbsp;&nbsp; offsetY,&nbsp;&nbsp; width,&nbsp;&nbsp; height} = contain(parentWidth, parentHeight, imageWidth, imageHeight)ctx.drawImage(image, offsetX, offsetY, width, height)
打开App,查看更多内容
随时随地看视频慕课网APP