【问题标题】:Windows 8.1: Exporting image from canvasWindows 8.1:从画布导出图像
【发布时间】:2026-02-10 23:35:02
【问题描述】:

我一直在用 JavaScript 编写 Windows 8 的绘图程序,但我偶然发现了一个问题。我不知道如何从画布中导出图像。我对 FileSavePicker 有点熟悉,但我需要帮助。

我找到了这个,但我不知道如何创建“编码”变量:Saving a Canvas as an image in Windows 8

如果有更简单的方法,或者如果有人可以解释,那将是一个很大的帮助。

【问题讨论】:

    标签: javascript canvas windows-8 export windows-8.1


    【解决方案1】:

    您可以使用 canvas.toDataURL() 从您的画布创建图像。

    然后您可以像这样在新窗口中打开该图像:

        var win=window.open();
        win.document.write("<img src='"+canvas.toDataURL()+"'/>");
    

    您的用户可以在该新窗口中执行通常的右键单击保存操作。

    这是工作代码:

    <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    
    <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>
    
    <script>
    $(function(){
    
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
    
        ctx.fillStyle="gold";
        ctx.strokeStyle="blue";
        ctx.lineWidth=5;
        ctx.rect(50,50,100,100);
        ctx.fill();
        ctx.stroke();
    
        var win=window.open();
        win.document.write("<img src='"+canvas.toDataURL()+"'/>");
    
    
    }); // end $(function(){});
    </script>
    
    </head>
    
    <body>
        <canvas id="canvas" width=300 height=300></canvas>
    </body>
    </html>
    

    【讨论】:

    • 谢谢,有机会我会试试的。
    • 好的。我从画布上得到了图像文件。但是有没有办法使用 fileSavePicker 让用户保存图像?
    • 您可以尝试直接使用fileSavePicker,但您可能会遇到跨域安全问题,具体取决于您的画布内容的来源。这是使用 fileSavePicker 的链接:my.safaribooksonline.com/book/…
    • 我不太明白如何使用它。你能给我举个例子吗?也许有一种方法可以将其转换为叮咬并保存,有可能吗?
    【解决方案2】:

    最终为了解决使用 Html 制作 Windows 8 应用程序的几个问题,我改用 C# 和 Xaml。

    我以前喜欢 Html 和 JavaScript,因为它们很熟悉,但在我对 Xaml 和 C# 有了更多了解后,我开始更喜欢它了。例如,您可以使用&lt;Grid&gt;&lt;Border&gt;&lt;StackPanel&gt; 等,而不是对界面的几乎每个部分使用&lt;div&gt;。但是对于这个特殊的问题,我很快就解决了。

    public async void Preview_Update()
    {
        RenderTargetBitmap bitmap = new RenderTargetBitmap();
        await bitmap.RenderAsync(canvas);
        image.Source = bitmap;
    }
    

    对于 FileSavePicker,它非常简单:FileSavePicker

    【讨论】: