How To Save Html5 Canvas To Image File Example

This article will tell you how to save the canvas shapes to an image file after you draw them. The image file can not be saved to your local computer file system in javascript directly, it is a base64 encoded binary string that can be assigned to the Html <img> tag’s src attribute, or send to another application ( for example a new web browser tab ) to show it. Then you can save it to your local computer from the web browser.

1. How To Save Hmtl5 Canvas To Base64 Encoded Binary Image File Data.

  1. The Html5 canvas object’s toDataURL(type) method can create the Image file base64 encoded binary string data.
  2. The type parameter’s value defines the image format type, it’s value is a string like ‘image/png’, ‘image/jpeg’.
  3. And the method returns a binary string like below.
    data:image/png;base64,iVBORw0K...mCC
  4. Then you can assign the above base64 encoded binary string to the Html <img> tag’s src attribute to display it.
    imageTag.src = 'data:image/png;base64,iVBORw0K...mCC';
  5. You can also display the image data in the web browser using the below javascript code.
    window.location = 'data:image/png;base64,iVBORw0K...mCC';
  6. But if you run the javascript code in step5 on the Google Chrome web browser, you may encounter the error Not allowed to navigate top frame to data URL. We will tell you how to fix it in the next section.

2. How To Fix The Error Not allowed to navigate top frame to data URL.

  1. Google Chrome does not allow using data URL as the URL address for security reasons.
  2. So when you paste the data URL into the Google Chrome URL address and press enter key, you can see the error in the Google Chrome web browser inspector’s Console tab ( please refer to How To Find Web Element Using Web Browser Inspector ).
  3. To fix this error, you can run the below javascript code to create a <iframe> tag and show the data URL as the iframe source page.
    var win = window.open();
    win.document.write('<iframe src="data:image/png;base64,iVBORw0K...mCC" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>')
    

3. Save Html5 Canvas To Base64 Encoded Image File Data Example.

  1. When you click the button Draw Rectangle & Save To Image, it will draw a red rectangle on the canvas and generate the canvas image file data and display the data in the Html <img> tag below the canvas.
  2. If you use Google Chrome, it will open a new tab and show the image data in an iframe tag.
  3. If you use other web browsers, it will open the image data in the new web browser tag directly.
  4. Below is the example result picture.
    how-to-save-html5-canvas-to-image-file-example
  5. This example contains 2 source files, html5-save-canvas-to-image-file.html, html5-save-canvas-to-image-file.js.
  6. html5-save-canvas-to-image-file.html.
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="ISO-8859-1">
    <title>How To Save Html5 Canvas To Image File</title>
    <script type="text/javascript" src="html5-save-canvas-to-image-file.js" charset="utf-8"></script>
    <style>
    canvas{
      display:block;
      margin-top:10px;
    }
    </style>
    </head>
    <body>
    <h3>How To Save Html5 Canvas To Image File.</h3>
    <div style="display:block;margin-top: 10px;">
        <input type="button" value="Draw Rectangle & Save To Image" onclick="drawSaveRectangle('canvas1', 'canvasImageDiv')" />
    </div>
    <canvas id="canvas1"></canvas>
    <div id="canvasImageDiv" style="display: none;margin-top: 10px;" >
    <label>The canvas image:</label>
    <img />
    </div>
    </body>
    </html>
  7. html5-save-canvas-to-image-file.js.
    function drawSaveRectangle(canvasId, imageDivId){
    
       // Get the html canvas object.
       var canvas = document.getElementById(canvasId);
       
       if(canvas==null){
           
           alert("Can not find the html element with element id " + canvasId);
           
           return false;
           
       }
    
       canvas.width = 600;
       canvas.height = 300;
       canvas.style.display = 'block';
       canvas.style.backgroundColor = 'blue';
       
       ctx = canvas.getContext('2d');
       
       ctx.fillStyle = 'red';
       ctx.fillRect(10,10,300,200);
    
       imageFileURL = canvas.toDataURL('image/png');
    
       var win = window.open();
    
       if(navigator.userAgent.indexOf("Chrome") == -1 ) {
          // can work on firefox, opera, microsoft edge. 
          win.location = imageFileURL;
       }else{
          // can work on google chrome to avoid the error html5-save-canvas-to-image-file.js:25 Not allowed to navigate top frame to data URL    
          win.document.write('<iframe src="' + imageFileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>')
       }
    
       var canvasImageDiv = document.getElementById(imageDivId);
       canvasImageDiv.style.display = 'block';
    
       var canvasImage = null;
    
       var childNodes = canvasImageDiv.childNodes;
       var len = childNodes.length;
    
    
       for(var i=0;i<len;i++){
    
            var childNode = childNodes[i];
            var tagName = childNode.tagName;
            if(tagName)        {
                if(tagName.toLowerCase() == 'img'){
    
                    canvasImage = childNode;
        
                    break;
        
                }
            }
            
    
       }
    
       canvasImage.width = 600;
       canvasImage.height= 300;
       canvasImage.style.display = "block";
       canvasImage.src = imageFileURL;
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x