视频截图加水印怎么实现?canvas绘制有问题

程序猿庆玲 阅读 49

我用video标签播放视频,想在用户点击截图时把当前画面转成带水印的图片。但水印文字总是显示不出来,或者位置不对,是不是drawImage和fillText的顺序有问题?

我试过先画视频帧再写文字,也试过反过来,但要么水印被覆盖,要么根本看不到。下面是我现在的代码:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
ctx.font = '20px Arial';
ctx.fillStyle = 'white';
ctx.fillText('© MySite', 10, 30);
我来解答 赞 7 收藏
二维码
手机扫码查看
2 条解答
东方冠羽
最简单的办法是确保水印文字在视频帧之后绘制,你现在的代码顺序是对的,问题可能出在视频帧还没完全加载上,加个回调试试:
video.requestVideoFrameCallback(() => {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
ctx.font = '20px Arial';
ctx.fillStyle = 'white';
ctx.fillText('© MySite', 10, 30);
});
点赞
2026-03-21 15:21
皇甫俊杰
顺序没毛病,应该是白色字在视频上看不清。加个黑色描边或者阴影就行,我给你写了段带阴影的代码,应该能解决。

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;

// 先画视频
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

// 设置字体和阴影,防止白色字看不清
ctx.font = 'bold 24px Arial';
ctx.fillStyle = 'white';
ctx.textBaseline = 'top';
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 4;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;

// 再画水印
ctx.fillText('© MySite', 20, 20);

// 导出图片看看
// const imgUrl = canvas.toDataURL('image/png');
点赞 2
2026-03-04 02:10