Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Save drawing as an image using HTML5 Canvas

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 876
    Comment on it

    Save drawing as an image using HTML5 Canvas


    Hello friends, today I am going to tell you how to save your drawing as an image using HTML5 canvas. Before starting, let us understand what is canvas. Canvas is used to draw graphics using javascript. It is used to draw graphs, or make photo compositions or do simple animations. Here is the simple example of canvas.


    <canvas id="mycanvas" width="100" height="100"></canvas>


    Now lets start drawing and save canvas drawing as an image. To do this we can set the source of an image object to the image data URL.  When the image is drawn, then user can save it by right clicking and saving it on their local system. Users can also open a new browser window directly with the image data url and the user could save it from there. It is the alternative way of saving the image. Now write the following code in your file and save it and then run it on the browser.



          body {
            margin: 0px;
            padding: 0px;
        <canvas id="myCanvas" width="578" height="200" style="display:none;"></canvas>
        <img id="canvasImg" alt="Right click to save me!">
          var canvas = document.getElementById('myCanvas');
          var context = canvas.getContext('2d');
          // draw cloud
          context.moveTo(170, 80);
          context.bezierCurveTo(130, 100, 130, 150, 230, 150);
          context.bezierCurveTo(250, 180, 320, 180, 340, 150);
          context.bezierCurveTo(420, 150, 420, 120, 390, 100);
          context.bezierCurveTo(430, 40, 370, 30, 340, 50);
          context.bezierCurveTo(320, 5, 250, 20, 250, 50);
          context.bezierCurveTo(200, 5, 150, 20, 170, 80);
          context.lineWidth = 5;
          context.fillStyle = '#8ED6FF';
          context.strokeStyle = '#0000ff';
          // save canvas image as data url (png format by default)
          var dataURL = canvas.toDataURL();
          // set canvasImg image src to dataURL
          // so it can be saved as an image
          document.getElementById('canvasImg').src = dataURL;


    Note:  toDataURL() is the method that requires any images drawn onto the canvas are hosted on a web server. SECURITY_ERR exception will be thrown if this condition is not met.


    Thanks for reading.


 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: