How to download a image that's on HTML5 canvas

2019-02-26 02:40发布

问题:

I wrote this webRTC app which takes photos with different filters added onto it. When I click on the click button, the frame from the webRTC video feed is loaded onto the canvas on the right side.

HTML Code -

<video id="vid" autoplay="true"></video>
<canvas id="cvs"></canvas>
<button id="btn1" onclick="start()">Start</button>
<button id="btn2" onclick="change()">Change Filter</button>
<button id="btn3" onclick="snap()" ng-click="random()">Click</button>

The function I've written to snap the picture onto the canvas after adding the filter is as follows

function snap() 
    {
    canvas.className = '';
    if (findex != 0)
    canvas.classList.add(filters[findex]);
    canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
    }

How can I allow the user to download the image onto the computer from the canvas with the filters after the photo has been clicked ?

回答1:

You can do this by using the .toDataURL() method on the canvas element. And then apply this to the download attribute to an <a> tag. We can add an anchor tag around the image:

<a>
    <canvas width="300" height="300" id="canvas"></canvas>
</a>

Now for the clicking on the canvas, we adjust the download and href of the <a> parent:

$('#canvas').click(function(){
     $(this).parent().attr('href', document.getElementById('canvas').toDataURL());
     $(this).parent().attr('download', "myPicture.png");    
});

Here is an example



回答2:

You might also consider using Concrete.js, which is a lightweight HTML5 Canvas Framework that does peripheral stuff like this, including downloads. You would just do:

canvas.download({
  fileName: 'my-file.png'
});