Category : Html | Author : Chtiwi Malek | First posted : 11/15/2012 | Updated : 12/6/2012
Tags : tutorial, canvas, html5, picture, img, html 5, ajax, upload, save
Draw a Canvas image, Upload and save it on the server

Draw a Canvas image, Upload and save it on the server

In this tutorial I will draw a picture on a Html 5 Canvas element and send it to the server to be stored.

When the user presses the “Draw Picture” button, a gradient and some  text will be drawn to onto the canvas element and when the user presses "Send image to the server" button, the script extracts the image data from the Canvas and upload it to your server. The server side code in this tutorial is written with Asp.Net C#.

First we create a Html page containing 3 elements :

1 - The canvas element: we will actually draw things onto the canvas using javascript.
2 - The "Draw picture" button.
3 - "Save canvas to server" button : this action will send the Image data to the server to be saved as a file.
          <form id="form1" runat="server">
               <script src="//" type="text/javascript"></script>
               <script type="text/javascript" src="JsCode.js"></script>
               <div align="center">
                    <canvas id="myCanvas" width="300" height="200"></canvas>
                    <br /><br />
                    <table><tr><td><button onclick="javascript:DrawPic();return false;">Draw Picture</button></td><td><button onclick="javascript:UploadPic();return false;">Upload Picture to Server</button></td></tr></table>

Then we write the 2 javascript functions DrawPic() and UploadPic() inside a javascript file "JsCode.js" (referenced earlier in the html code)  :
function DrawPic() {
    // Get the canvas element and its 2d context
    var Cnv = document.getElementById('myCanvas');
    var Cntx = Cnv.getContext('2d');
    // Create gradient
    var Grd = Cntx.createRadialGradient(100, 100, 20, 140, 100, 230);
    Grd.addColorStop(0, "red");
    Grd.addColorStop(1, "black");
    // Fill with gradient
    Cntx.fillStyle = Grd;
    Cntx.fillRect(0, 0, 300, 200);
    // Write some text
    for (i=1; i<10 ; i++)
        Cntx.fillStyle = "white";
        Cntx.font = "36px Verdana";
        Cntx.globalAlpha = (i-1) / 9;
        Cntx.fillText("", i * 3 , i * 20);
function UploadPic() {
    // Generate the image data
    var Pic = document.getElementById("myCanvas").toDataURL("image/png");
    Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "")

    // Sending the image data to Server
        type: 'POST',
        url: 'Save_Picture.aspx/UploadPic',
        data: '{ "imageData" : "' + Pic + '" }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert("Done, Picture Uploaded.");
And finally our C# server-side code snippet, we create a blank aspx page with the following code behind to read and save the picture :
using System;
using System.Web;
using System.IO;
using System.Web.Script.Services;
using System.Web.Services;
public partial class Save_Picture : System.Web.UI.Page
    public static void UploadPic (string imageData)
        string Pic_Path = HttpContext.Current.Server.MapPath("MyPicture.png");
        using (FileStream fs = new FileStream(Pic_Path, FileMode.Create))
            using (BinaryWriter bw = new BinaryWriter(fs))
                byte[] data = Convert.FromBase64String(imageData);
A sample website to run and test this code is available in the attached file, Thanks.
About the author :
Malek Chtiwi is the man behind
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.
Comments & Opinions :
Php server side code
Thanks, Php server side code would be like :

  if (array_key_exists('imageData',$_REQUEST)) {
    $imgData = base64_decode($_REQUEST['imageData']);

    // Path where the image is going to be saved
    $filePath = '/uploads/myImage.png';

    // Delete previously uploaded image
    if (file_exists($filePath)) { unlink($filePath); }

    // Write $imgData into the image file
    $file = fopen($filePath, 'w');
    fwrite($file, $imgData);
- by Arnauld on 11/16/2012
not working.. it returns null
- by sak on 10/30/2015
Thanking you
your article help me alot...thanking you once again.
- by Naisarg on 8/1/2013
works as is but doesn't work when a canvas thats filled with an image
hello, i changed the code so that instead of painting the canvas, it fills the canvas with a jpg image file. I then manipulate the image in the canvas and need to save the canvas as a png file. The problem is that I cant get that to happen. The only code I changed was the DrawPic() function as shown below:
function DrawPic() {
             var canvas = document.getElementById('myCanvas');
             var context = canvas.getContext('2d');
             var imageObj = new Image();          
             var x = 0;
             var y = 0;
             var width = 400;
             var height = 400;
             var imageObj2 = new Image();
             var contextovl = canvas.getContext('2d');

             imageObj.onload = function () {
                 context.globalAlpha = 1;
                 context.drawImage(imageObj, x, y, width, height);
             imageObj.src = 'img/cat.jpg';

             imageObj2.onload = function () {
                 contextovl.globalAlpha = .5;
                 contextovl.drawImage(imageObj2, x, y, width, height);

             imageObj2.src = 'img/sillyoverlay.png'; }
What I see in my canvas is exactly what I want, i just need to save it to a .png file..

Any help would be apprecited. I don't get any errors when I hit the uploadpic button, its just that nothing happens.
- by Jim on 7/1/2015
I have thats same problem like u i make work it on mozilla only
u must just make new blob for canvas and will be work
- by korgan on 9/15/2015
Thank's a lot
im working in a application with canvas js, and your example helped me of great way
Greetings from Mexico
- by Nicolas JL on 9/29/2015
C# codeBehind
Is JavaScript the only methot to draw into HTML5 Canvas Tag?
Do you think in C# aspx webform code behind can?
- by Victor on 1/5/2016
Thank for code
I changed code from DrawPic() to load from image source instead.
The problem was it's not save to server when set new width & height to canvas
for display original size of image

    <script type="text/javascript">
        $(document).ready(function () {
            var c = document.getElementById("myCanvas");            
            var ctx = c.getContext("2d");
            var img = new Image();
            img.onload = function () {
                var w = this.width;
                var h = this.height;
                //c.width = w; // error when set width, height to canvas 
                //c.height = h;
                ctx.drawImage(img, 0, 0);
            img.src = 'http://localhost/tryout/webix/B0032737.jpg';
- by Aod47 on 4/7/2016
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :