以下代码拍摄图像,将其复制到画布中(因此可以修改),然后再将其转换为图像:
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()
。但是,这不起作用。我明白了:
不允许将顶部框架导航到数据网址: 数据:图像/ PNG; BASE64,iVBORw0KG .......
这样做的正确方法是什么?我需要将图像自动下载到用户的计算机上。
答案 0 :(得分:1)
您可以使用canvas.toBlob()
获取文件的Blob
,创建一个新的Blob
,其原始Blob
设置为可迭代,type
设置为{ {1}},"application/octet-stream"
创建文件对象的URL.createObjectURL()
。
Blob URL
答案 1 :(得分:1)
以下是示例代码..!
<!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>