在Canvas中模拟CSS的“background-size: cover”
在canvas上绘制图片时,可能会遇到图片被覆盖的问题伸展。为了实现所需的“覆盖”功能(按比例缩放图像以适合给定容器),需要一种更复杂的方法。
一个解决方案是以下 JavaScript 函数:
/** * 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 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 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);按比例缩放图像以适合容器内部。
- 要偏移图像,请使用最后两个参数:drawImageProp(ctx, image, 0, 0, width, height, offsetX, offsetY);。偏移量范围从 0.0(左/上)到 1.0(右/下)。
以上是如何在Canvas中模拟CSS的`background-size: cover`?的详细内容。更多信息请关注PHP中文网其他相关文章!

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatoryand and powerincreatingsmoothcssanimations.keytricksinclude:1)definingsmoothtransitionsbetnestates,2)使用AnimatingmatematingmultationmatingMultationPropertiessimultane,3)使用使用4)使用BombingeNtibalibility,4)使用BombingingWithjavofofofofofoffo

CSSCOUNTERSAREDOMANAGEAUTOMANAMBERINGINWEBDESIGNS.1)他们可以使用forterablesofcontents,ListItems,and customnumbering.2)AdvancedsincludenestednumberingSystems.3)挑战挑战InclassINCludeBrowsEccerCerceribaliblesibility andperformiballibility andperformissises.4)创造性

使用滚动阴影,尤其是对于移动设备,是克里斯以前涵盖的一个微妙的UX。杰夫(Geoff)涵盖了一种使用动画限制属性的新方法。这是另一种方式。

文章讨论了CSS FlexBox,这是一种布局方法,用于有效地对齐和分布响应设计中的空间。它说明了FlexBox用法,将其与CSS网格进行了比较,并详细浏览了浏览器支持。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

Dreamweaver Mac版
视觉化网页开发工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。