0

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.

alex
  • 7,111
  • 15
  • 50
  • 77
  • 1
    see answer here: https://stackoverflow.com/questions/10673122/how-to-save-canvas-as-an-image-with-canvas-todataurl does it work? – Kresimir Pendic Jan 12 '18 at 09:00

2 Answers2

2

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
})
guest271314
  • 1
  • 15
  • 104
  • 177
0

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>
Tushar Acharekar
  • 880
  • 7
  • 21