提问人:btgen 提问时间:11/3/2022 最后编辑:ggorlenbtgen 更新时间:11/9/2023 访问量:1858
将画布作为 WebP 图像返回
return canvas as webp image
问:
如何将此函数上的画布作为 webp 图像返回?
function capture(video) {
if(scaleFactor == null){
scaleFactor = 1;
}
//var w = video.videoWidth * scaleFactor;
//var h = video.videoHeight * scaleFactor;
var w = 700;
var h = 400;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var uniq = 'img_' + (new Date()).getTime();
canvas.setAttribute('id', uniq);
return canvas ;
}
答:
4赞
Salim
11/3/2022
#1
Canvas 有一个称为 的方法。.toDataURL(type, encoderOptions)
在这种情况下,以下片段就足够了
canvas.toDataURL('image/webp');
这将为您提供一个数据 URL,它是图像的 base64 编码,如下所示
data:image/webp;base64,UklGRqgCAABXRUJQVlA4WAoAAAAwAAAAxwAAYwAASUNDUBgCAAAAAAIYAAAAAAQwAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAAHRyWFlaAAABZAAAABRnWFlaAAABeAAAABRiWFlaAAABjAAAABRyVFJDAAABoAAAAChnVFJDAAABoAAAAChiVFJDAAABoAAAACh3dHB0AAAByAAAABRjcHJ0AAAB3AAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAFgAAAAcAHMAUgBHAEIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFhZWiAAAAAAAABvogAAOPUAAAOQWFlaIAAAAAAAAGKZAAC3hQAAGNpYWVogAAAAAAAAJKAAAA+EAAC2z3BhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABYWVogAAAAAAAA9tYAAQAAAADTLW1sdWMAAAAAAAAAAQAAAAxlblVTAAAAIAAAABwARwBvAG8AZwBsAGUAIABJAG4AYwAuACAAMgAwADEANkFMUEgPAAAAAQcQEREAUKT//yWi/6lwAFZQOCBSAAAA8AcAnQEqyABkAD5tNplJpCMioSBoAIANiWlu4XXwADuh1VJsmIdVSbJiHVUmyYh1VJsmIdVSbJiHVUmyYh1VJsmIdVSbJhYAAP7/wbAAAAAAAA==
更多信息可以在 https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL 上找到
评论
0赞
btgen
11/3/2022
你能举例说明基于我的代码的实现吗?
2赞
Salim
11/4/2022
@btgen 您只需要返回 canvas.toDataUrl 而不是 canvas。此数据 url 将适用于图像标记中现代浏览器中的 src 参数。
评论