小程序的视频容器背景色是微信厂商不支持替换的,如果有特殊需求要求背景变更或者动态调整样式需要解决 可以试着使用如下方案,本文使用的是react和taro相关技术
在视频组件中,在初次渲染组件的时候,获取视频封面图片的宽高尺寸,以及预设定的容器宽高尺寸
使用阿里云oss视频的时候 添加?x-oss-process=video/snapshot,t_1,m_fast可以获取首帧图片
video-warp-currentIndex为预设的容器大小
jsuseEffect(() => {
Taro.getImageInfo({
src: videoUrl + '?x-oss-process=video/snapshot,t_1,m_fast',
success: (res) => {
const query = Taro.createSelectorQuery()
query.select('#video-warp').boundingClientRect(data => {
if (data) {
applyObjectFitContain(res, data)
}
}).exec()
},
fail: (err) => {
console.info('🚀 ~ file:fail -----', '图片宽高获取失败')
}
})
}, [])
定义方法applyObjectFitContain
js// 声明组件内的局部变量
const [videoStyleState, setVideoStyleState] = useState({
direction: '',
widthPx: 0,
heightPx: 0
})
// 方法applyObjectFitContain
function applyObjectFitContain(videoElement, containerElement) {
// 获取视频和容器的宽高
const videoWidth = videoElement.width;
const videoHeight = videoElement.height;
const containerWidth = containerElement.width;
const containerHeight = containerElement.height;
let directionStr = ''
// 计算屏幕和图片的比例
const imageRatio = videoWidth / videoHeight;
// 获取垂直高度
let heightPx = 0
let widthPx = 0
if (imageRatio < 1) {
directionStr = 'vertical'
heightPx = (containerWidth / imageRatio).toFixed(2)
if (heightPx > containerHeight) {
// 如果得到的高度大于容器高度 则以高度为边计算
widthPx = (containerHeight / (videoHeight / videoWidth)).toFixed(2)
}
} else {
directionStr = 'horizontal'
// 获取垂直高度
heightPx = (containerWidth * (videoHeight / videoWidth)).toFixed(2)
}
if (widthPx) {
console.info('🚀 ~ method:applyObjectFitContain-----', `direction=${directionStr}---widhtPx=${widthPx}`)
} else {
console.info('🚀 ~ method:applyObjectFitContain-----', `direction=${directionStr}---heightPx=${heightPx}`)
}
setVideoStyleState(() => (
{
direction: directionStr,
widthPx,
heightPx
}
))
}
组件的内联样式
js// 外层应该有容器 id = video-warp
<Video
style={{
'width': videoStyleState.widthPx ? (videoStyleState.widthPx + 'px') : '100%',
'height': videoStyleState.heightPx ? (videoStyleState.heightPx + 'px') : '100%'
}}
src={videoUrl}
objectFit="contain"
controls={false}>
</Video>
代码经测试可解决video自适应宽高动态设置位置
本文作者:seek
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!