页面有一个video视频,以及一个按钮,点击按钮时将视频画面进行截图,安装了"wxml-to-canvas": "^1.1.1",截图下来后发现图片都是黑屏的,应该怎么解决?
wxml
<view class="container">
<video id="myVideo" src="{{videoSrc}}" controls autoplay></video>
<button bindtap="captureScreenshot">截取视频</button>
<canvas canvas-id="videoCanvas" style="width: 300px; height: 200px;"></canvas>
</view>
wxss
.container {
display: flex;
flex-direction: column;
align-items: center;
}
video {
width: 100%;
height: 200px;
}
button {
margin-top: 10px;
}
js
Page({
data: {
videoSrc: 'https://media.w3.org/2010/05/sintel/trailer.mp4', // 替换为实际视频链接
},
captureScreenshot: function () {
const videoContext = wx.createVideoContext('myVideo');
videoContext.pause(); // 暂停视频,以便捕获当前帧
const query = wx.createSelectorQuery();
query.select('#myVideo').boundingClientRect();
query.select('#videoCanvas').boundingClientRect();
query.exec((res) => {
const videoRect = res[0];
const canvasRect = res[1];
const canvasContext = wx.createCanvasContext('videoCanvas');
// 使用CanvasContext绘制视频帧
canvasContext.drawImage(this.data.videoSrc, 0, 0, videoRect.width, videoRect.height);
canvasContext.draw(false, () => {
wx.canvasToTempFilePath({
canvasId: 'videoCanvas',
success: (res) => {
console.log('Canvas image path:', res.tempFilePath);
// 预览图片
wx.previewImage({
urls: [res.tempFilePath],
current: res.tempFilePath
});
},
fail: (err) => {
console.error('截图失败', err);
}
});
});
});
}
});
建议使用官方的demo
https://developers.weixin.qq.com/miniprogram/dev/framework/ability/canvas.html#%E5%BD%95%E5%88%B6%E8%A7%86%E9%A2%91