gpt4 book ai didi

javascript - 如何自动下载从 Canvas 元素获取的图像?

转载 作者:行者123 更新时间:2023-12-03 02:43:12 25 4
gpt4 key购买 nike

以下代码获取图像,将其复制到 Canvas 中(以便可以对其进行修改),然后再次将其转换为图像:

  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()。然而,这不起作用。我得到:

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

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

最佳答案

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

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

关于javascript - 如何自动下载从 Canvas 元素获取的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48222660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com