【问题标题】:How to automatically download a image taken from a canvas element?如何自动下载从画布元素中获取的图像?
【发布时间】:2018-06-21 16:52:54
【问题描述】:

以下代码获取一张图片,将其复制到画布中(以便对其进行修改),然后再次将其转换为图片:

  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

如您所见,我正在尝试自动下载图像:window.location = canvas.toDataURL()。但是,这不起作用。我明白了:

不允许将顶部框架导航到数据 URL: 数据:图片/png;base64,iVBORw0KG.......

这样做的正确方法是什么?我需要将图像自动下载到用户的计算机上。

【问题讨论】:

标签: javascript html canvas


【解决方案1】:

您可以使用canvas.toBlob() 获取文件的Blob,创建一个新的Blob,将原始Blob 设置为可迭代,将type 设置为"application/octet-stream"URL.createObjectURL() 创建一个@文件对象的987654332@。

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

【讨论】:

【解决方案2】:

下面是示例代码..!

<!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>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
  • 2014-11-06
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多