How to save an image from canvas

前端 未结 4 569
借酒劲吻你
借酒劲吻你 2020-12-17 01:07

Recently I\'ve been attempting to create a photo booth by relying on Webrtc and have nearly completed all of the code except I\'ve not been able to figure out a way to save

4条回答
  •  一生所求
    2020-12-17 01:44

    If I understand correctly you want to download (ie. provide a save dialog for the user to pick a location) the image to user's machine?'

    If so you can use this snippet:

    function download(canvas, filename) {
    
        /// create an "off-screen" anchor tag
        var lnk = document.createElement('a'),
            e;
    
        /// the key here is to set the download attribute of the a tag
        lnk.download = filename;
    
        /// convert canvas content to data-uri for link. When download
        /// attribute is set the content pointed to by link will be
        /// pushed as "download" in HTML5 capable browsers
        lnk.href = c.toDataURL();
    
        /// create a "fake" click-event to trigger the download
        if (document.createEvent) {
    
            e = document.createEvent("MouseEvents");
            e.initMouseEvent("click", true, true, window,
                             0, 0, 0, 0, 0, false, false, false,
                             false, 0, null);
    
            lnk.dispatchEvent(e);
    
        } else if (lnk.fireEvent) {
    
            lnk.fireEvent("onclick");
        }
    }
    

    Now all you need to do is to provide a default file name and call the function:

    download(myCanvas, 'untitled.png');
    

    If you rather than this mean save directly to user's harddisk then you can't due to security reasons.

    That being said, there is always the option of using local storage such as File API or Indexed DB - but as these are sand-boxed you and the user will only have access to the "files" through the browser so perhaps not so convenient.

提交回复
热议问题