首页 > 解决方案 > Javascript,将照片从相机(画布)存储到本地/服务器

问题描述

问题

我正在使用这个网站的 javascript。

https://developers.google.com/web/fundamentals/media/capturing-images/#acquire_access_to_the_camera

有关于画布的信息,我可以:

例如,我如何从画布存储到本地或服务器?那么时髦的效果呢?:)

并且是否可以在没有查看相机video tag窗口的情况下将输入从相机存储到文件?

谢谢。

系统

Linux local 5.0.0-29-lowlatency #31-Ubuntu SMP PREEMPT Thu Sep 12 14:13:01 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

更新

标签: javascriptimagestore

解决方案


您可以使用以下命令将图像 src 保存为 base64 canvas.toDataURL("img/png")

captureButton.addEventListener('click', () => {
    // Draw the video frame to the canvas.
    context.drawImage(player, 0, 0, canvas.width, canvas.height);
    // Get the image src (base64)
    const imgSrc=canvas.toDataURL("img/png");

    // Apply the src to an image element
    const img = new Image();
    img.src = imgSrc

    // Add the newly created image to the DOM
    // A html element with the class .image-holder needs to exist on the page
    document.querySelector('.image-holder').appendChild(img);

    // Store the src in local storage
    localStorage.setItem('imgSrc', imgSrc)
  });

要将其保存到本地计算机,您可以使用FileSaver之类的东西(感谢这个SO 答案):

captureButton.addEventListener('click', () => {
    // Draw the video frame to the canvas.
    context.drawImage(player, 0, 0, canvas.width, canvas.height);

    // save the file
    canvas.toBlob(function(blob) {
        saveAs(blob, "image-name.jpg");
    });
  });

编辑:这里的工作示例https://codepen.io/relativemc/pen/QWLoOZO


推荐阅读