【问题标题】:How to take an image of a stream and download it如何拍摄流的图像并下载它
【发布时间】:2020-08-16 18:09:10
【问题描述】:

我正在尝试对相机网站进行编程。流似乎可以工作,我可以看到画布在绘制时捕获了它的图像,但是在将其更改为图像然后下载它时,我似乎遇到了问题。求救

function capture() {
var canvas = document.getElementById('canvas');     
var video = document.getElementById('video');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 140, 0, video.videoWidth, video.videoHeight);
var data = canvas.toDataURL();
var prev = window.location.href;
window.location.href = data.replace("image/png", "image/octet-stream");
window.location.href = prev;

【问题讨论】:

  • 能否确保您提供的代码足以让我们调试问题?了解如何制作minimal reproducible example
  • 这个link 可能有用。在您的情况下,您需要设置 a.href = canvas.toDataURL(); 此更改与上述链接中的代码进行比较

标签: javascript jquery


【解决方案1】:

将您的代码替换为以下内容,注意“capture.png”需要替换为您要将文件另存为的实际文件名。 'image/png' 具有 mime 类型,当 mimeType 为 image/jpeg 或 image/webp 时,该 toBlob 函数具有第三个质量参数。

var canvas = document.getElementById('canvas');     
var video = document.getElementById('video');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 140, 0, video.videoWidth, video.videoHeight);
var blob = canvas.toBlob(function (blob) {
var anchor = document.createElement('a');
anchor.style.display = 'none';
document.body.appendChild(anchor);
var url = window.URL.createObjectURL(blob);
anchor.href = url;
anchor.download = 'capture.png';
anchor.click();
window.setTimeout(() => {
    window.URL.revokeObjectURL(url);
    document.body.removeChild(anchor);
  }, 100);
}, 'image/png');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-12
    • 2013-03-20
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 2020-07-06
    • 1970-01-01
    相关资源
    最近更新 更多