我有一个脚本将canvas元素转换为base64编码图像,将其设置为链接的href
,并允许用户将其下载为jpeg。我
在开发工具中,我可以打开数据网址并查看图片,我已经确认链接的href
已正确更新。但是,无法查看下载的文件。试图在PhotoShop中打开它会显示以下错误:
无法完成您的请求,因为JPEG标记段长度 太短(文件可能被截断或不完整)。
是什么导致这个?
以下是在click上设置href
值的函数:
$(a).click(function() {
var e = r.toDataURL("image/jpeg");
console.log(e); //Verify base64 encoded image which works correctly
a.href = e;
});
答案 0 :(得分:0)
以下适用于我。我怀疑您的问题可能与浏览器兼容性有关。
<h1>Copy graphic using toDataURL</h1>
<div>
<button id="copy">Copy canvas image to image element</button> <br />
<canvas id="MyCanvas" width="400" height="400" >This browser or document mode doesn't support canvas</canvas>
<img id="MyPix" src="" width="400" height="400" />
<a id="myAnchor" href="#" download>Some Link that should download whatever it's pointing to</a>
</div>
<script>
// Create some graphics on the canvas.
var canvas = document.getElementById("MyCanvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.beginPath();
ctx.rect(5, 5, 300, 250);
ctx.fill();
ctx.stroke();
ctx.arc(150, 150, 100, 0, Math.PI, false);
ctx.stroke();
}
// catch the click from the button and copy the graphic
document.getElementById("copy").addEventListener("click", function () {
var canvas1 = document.getElementById("MyCanvas");
var anchor = document.getElementById("myAnchor");
if (canvas1.getContext) {
var ctx = canvas1.getContext("2d"); // Get the context for the canvas.
var myImage = canvas1.toDataURL("image/jpeg"); // Get the data as an image.
}
var imageElement = document.getElementById("MyPix"); // Get the img object.
imageElement.src = myImage; // Set the src to data from the canvas.
anchor.href = myImage;
}, false);
</script>
答案 1 :(得分:0)
我认为在点击事件中设置Href是个坏主意。在点击之前尝试设置它。看到这段代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<a id="link" href="#">Download</a>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(150, 150);
ctx.arc (100,75,50,0,2*Math.PI);
context.closePath();
context.lineWidth = 3;
context.strokeStyle = '#444';
context.stroke();
var dataURL = canvas.toDataURL();
document.getElementById("link").href = dataURL;
</script>
</body>
</html>
它将绘制一个圆,然后直接设置链接的HREF。这样可以正常工作。