【问题标题】:Download a Html5 canvas element as an image with the file extension with Javascript下载一个 Html5 画布元素作为带有 Javascript 文件扩展名的图像
【发布时间】:2023-03-08 21:41:01
【问题描述】:

我希望能够将 Html5 画布元素下载为带有 Javascript 文件扩展名的图像。

CanvasToImage 库似乎无法实现这一点。

这是我目前的代码,您可以在JsFiddle 看到。

<div id="canvas_container">
</div>
<p>
<a href='#' id="create_image">create</a> 
<a href="#" id="download_image">download</a>
</p>




$("#create_image").click(function() {
var cnvs = createSmileyOnCanvas();
$('#canvas_container').append(cnvs);
});


$("#download_image").click(function() {    
var img = $('#smiley_canvas').toDataURL("image/png");
var uriContent = "data:application/octet-stream," + encodeURIComponent(img);
window.open(uriContent, 'download smiley image');
});



function createSmileyOnCanvas() {
var canvas = document.createElement('canvas');      
canvas.id = 'smiley_canvas';    
var ctx = canvas.getContext('2d');        

// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false);   // Mouth
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true);  // Left eye
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true);  // Right eye
ctx.stroke();

return canvas;
}

【问题讨论】:

    标签: javascript jquery html canvas


    【解决方案1】:

    这似乎对我有用:

    <a id="downloadImgLink" onclick="$('#downloadImgLink').attr('href', canvas.toDataURL());" download="MyImage.png" href="#" target="_blank">Download Drawing</a>

    【讨论】:

    • 画布的背景图像不包含在结果图像中。有没有办法也包括背景图片?
    • @faizi 你可能需要在画布上绘制它,而不是仅仅用 CSS 设置背景,这是你在做什么?
    【解决方案2】:

    为了在浏览器的下载对话框中强制/建议文件名,您需要发送 Content-Disposition: attachment; filename=foobar.png 标头。

    这不可能通过window.open 来实现,所以除非有一些特定于浏览器的黑客攻击,否则你很不走运。

    如果您确实需要文件名,可以尝试使用a&lt;a href="put stuff here" download="filename here"&gt; 中的新下载属性。不过,它还没有得到广泛的支持。

    另一种选择是首先使用 ajax 将数据提交到服务器,然后将浏览器重定向到某个服务器端脚本,然后该脚本将使用正确的标头提供数据。

    【讨论】:

    【解决方案3】:

    您好,我创建了一个 jquery 插件,它可以让您轻松完成相同的任务,但它也使用 php 下载图像。让我解释一下它是如何工作的

    插件有2个子函数,你可以独立调用将图像添加到画布,另一个是下载当前位于画布上的图像。

    将图像添加到画布

    为此,您需要传递画布元素的 id 和要添加的图像的路径

    从画布下载图片

    为此,您需要传递画布元素的 id

     $('body').CanvasToPhp.upload({
        canvasId: "canvas",   // passing the canvasId
        image: "455.jpg"      // passing the image path
    });
    
    // downloading file
    $('#download').click(function(){
        $('body').CanvasToPhp.download({
            canvasId: "canvas"   // passing the canvas id
        });  // 
    });
    

    首先你需要下载插件文件,你可以在这里找到http://www.thetutlage.com/post=TUT213

    我还创建了一个小演示http://thetutlage.com/demo/canvasImageDownload

    【讨论】:

    • 不错,你应该把它贴在 github 上。如果你这样做,请告诉我。
    猜你喜欢
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多