alex
alex

Reputation: 7601

How to automatically download a image taken from a canvas element?

The following code takes an image, copies it into a canvas (so it can be modified), then it turns it into an image again:

  const image = this.markerEditorEl.components.screenshot.getCanvas('perspective').toDataURL()
  var canvas = document.getElementById('test-canvas')
  var context = canvas.getContext('2d')
  var imageObj = new Image()

  imageObj.onload = function () {
    // set values
    const sourceWidth = cropWidth
    const sourceHeight = cropHeight
    const sourceX = (width / 2) - (sourceWidth / 2)
    const sourceY = (height / 2) - (sourceHeight / 2)
    const destWidth = cropWidth
    const destHeight = cropHeight
    const destX = 0
    const destY = 0
    context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight)
    window.location = canvas.toDataURL()
  }
  imageObj.src = image

As you can see, I'm trying to download the image automatically: window.location = canvas.toDataURL(). However, this doesn't work. I get:

Not allowed to navigate top frame to data URL: data:image/png;base64,iVBORw0KG.......

What's the correct way of doing this? I need the image to be automatically downloaded to the user's computer.

Upvotes: 0

Views: 2236

Answers (2)

Tushar Acharekar
Tushar Acharekar

Reputation: 900

Below is sample code..!

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the canvas element.
</canvas>
<button  onclick="downloadImage()">Save image</button>

<script  src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);

    function downloadImage(){
        var canvas = document.getElementById("myCanvas");
    	canvas.toBlob(function(blob) {
    		saveAs(blob, "canvas_images.png");
    	});
    }
</script>
</body>
</html>

Upvotes: 0

guest271314
guest271314

Reputation: 1

You can use canvas.toBlob() to get a Blob of the file, create a new Blob with original Blob set as iterable with type set to "application/octet-stream", URL.createObjectURL() to create a Blob URL of the file object.

canvas.toBlob(blob => {
  let file = new Blob([blob], {type:"application/octet-stream"})
  let blobURL = URL.createObjectURL(file)
  window.location.href = blobURL
})

Upvotes: 2

Related Questions