Stephen
Stephen

Reputation: 574

Windows 8.1: Exporting image from canvas

I've been working or sort of a paint program for Windows 8 in JavaScript, But I've stumbled upon a problem. I have no idea how to export a image from a canvas. I'm kind of familiar with the FileSavePicker but I need help.

I found this but I don't know how to create a "encoding" variable: Saving a Canvas as an image in Windows 8

If there's a simpler way or if someone could explain it that would be a great help.

Upvotes: 0

Views: 323

Answers (2)

Stephen
Stephen

Reputation: 574

Ultimately to solve several issues using Html to make a Windows 8 app, I switched to C# and Xaml.

I used to like Html and JavaScript because it was familiar, but after I learned more about Xaml and C# I started to like it better. For example, instead of using <div> for almost every section of interface, you can use a, <Grid>, <Border>,<StackPanel>, and more. But for this particular problem I solved it pretty quickly.

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

And for the FileSavePicker, it's pretty simple: FileSavePicker

Upvotes: 0

markE
markE

Reputation: 105035

You can use canvas.toDataURL() to create an image from your canvas.

Then you can open that image in a new window like this:

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

Your user can do the usual right-click-save in that new window.

Here's working code:

<!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>

Upvotes: 1

Related Questions