How to save svg canvas to local filesystem

前端 未结 16 1494
南旧
南旧 2020-11-27 10:10

Is there a way to allow a user, after he has created a vector graph on a javascript svg canvas using a browser, to download this file to their local filesystem?

SVG

16条回答
  •  盖世英雄少女心
    2020-11-27 10:19

    I maybe discovered a better way for not forcing the user to press right click "save image as". just live draw the canvas base64 code into the href of the link and modify it so the download will start automatically. i dont know if its universal browser compatible but it should work with the main/new browsers.

    var canvas = document.getElementById('your-canvas');
        if (canvas.getContext) {
            var C = canvas.getContext('2d');
        }
    
    $('#your-canvas').mousedown(function(event) {
        // feel free to choose your event ;) 
    
        // just for example
        // var OFFSET = $(this).offset();
        // var x = event.pageX - OFFSET.left;
        // var y = event.pageY - OFFSET.top;
    
        // standard data to url
        var imgdata = canvas.toDataURL('image/png');
        // modify the dataUrl so the browser starts downloading it instead of just showing it
        var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet-stream');
        // give the link the values it needs
           $('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);
    
    });
    

    feel free to wrap the a around anything you want, hope that helps a bit

提交回复
热议问题