JavaScript Canvas - Read/Writing Local Files
Written by Ian Elliot   
Monday, 22 February 2021
Article Index
JavaScript Canvas - Read/Writing Local Files
Writing A Local File

Writing a Local File

It is usually said that you cannot write a file to the user’s local file system. The reason is that if you could it would be a very big security problem. The truth of the situation is very similar to the case of reading a file from the local file system. You can write to the local file system, but the user is made aware of the operation and has to click an OK button to allow it to happen.

There is no “packaged” way to write a file. The basic method is to create a DOM HTMLAnchorElement, associated with <a>, set its href attribute to the URL of the file you want to save and its download attribute to the name of the file you want to save. You can then use its click method to simulate a user click on the link. Notice that, in Chrome, you don’t have to add the link object to the DOM and the user doesn’t have to see it. Firefox and some other browsers will only let you use the click method if the link is added to the DOM. However, it is easy to hide it by setting its display style to “none”.

When you call its click method, a file save dialog box opens and the user has to click the Save button to “download” the file. This ensures that you cannot sneak a file save past the user without them knowing about it.

For example, to save the current contents of a canvas to the local file system you would use:

async function saveCanvas(ctx) {
    var blob = await canvasToBlob(ctx, "image/png");
    var a = document.createElement('a');
    a.download = 'download.png';
    a.style.display = "none";
    document.body.appendChild(a);
    var url=URL.createObjectURL(blob);
    a.href = url;
    a.click();
    URL.revokeObjectURL(url);
}

where the canvasToBlob function was listed earlier in the chapter:

function canvasToBlob(ctx, type) {
       return new Promise(function (resolve, reject) {
                ctx.canvas.toBlob(function (blob) {
                                   resolve(blob);
                }, type);
       });
}

If you now try:

saveCanvas(ctx);

you will discover that a dialog box appears asking you to confirm the details of the save operation. There is, or there should be, no way to circumvent this dialog box. If you find one then you have broken the browser’s security.

In Chapter but not in this extract

 

  • Response
  • Working with the Server - Basic Fetch
  • Request Object
  • Downloading Graphics from the Server
  • Uploading Local Graphics
  • Using FormData
  • Upload Without a Form
  • Direct Binary Upload
  • The Data URL
  • SVG To Canvas – HTML To Canvas

Summary

  • The Blob is essentially a file but without a filename or other properties. You can consider it an unstructured stream of data.

  • A File is a blob with a filename and date and time of creation and use.

  • The FileReader object can be used to read the data associated with a File or a Blob.

  • You can open and read a file in the local file system but only if the user selects it via a File Open dialog box.

  • You can write a file to the local file system but only if the user is made aware of it via a File Save dialog box.

  • The Response object provides a stream-oriented and promise-based way of reading a file. For graphics data in most cases you would use the typed “read to the end” methods.

  • The Fetch API is a promise-based replacement for XMLHttpRequest.

  • The Request object customizes the request made by the Fetch API.

  • In most cases the simplest and fastest way to download graphics from a server is to use the Image object to download and decode the file format.

  • You can upload graphics data to the server with the help of a form and/or the FormData object. According to the MIME type you use this provides a great deal of automatic processing at the client and the server.

  • If you want to be in complete control of what is happening, you can use a direct binary upload of a file, but then you usually have to do more work at the server to retrieve the file.

  • A Data URL stores text or binary data within the URL itself. Binary data is stored as base64 encoded text.

  • You can use a Data URL to establish a link to render both SVG and HTML onto a canvas object.

Now available as a paperback or ebook from Amazon.

JavaScript Bitmap Graphics
With Canvas

largecover360

 

Contents

  1. JavaScript Graphics
  2. Getting Started With Canvas
  3. Drawing Paths
      Extract: Basic Paths 
      Extract: Bezier Curves 
  4. Stroke and Fill
      Extract: Stroke Properties 
      Extract: Fill and Holes
      Extract: Gradient & Pattern Fills 
  5. Transformations
      Extract: Transformations
      Extract: Custom Coordinates 
      Extract  Graphics State
  6. Text
      Extract: Text, Typography & SVG 
      Extract: Unicode 
  7. Clipping, Compositing and Effects
      Extract: Clipping & Basic Compositing 
  8. Generating Bitmaps
      Extract:  Introduction To Bitmaps
      Extract :  Animation 
  9. WebWorkers & OffscreenCanvas
      Extract: Web Workers **NEW!
      Extract: OffscreenCanvas
  10. Bit Manipulation In JavaScript
      Extract: Bit Manipulation  
  11. Typed Arrays
  12. Files, blobs, URLs & Fetch
      Extract: Blobs & Files
      Extract: Read/Writing Local Files 
  13. Image Processing
      Extract: ImageData
      Extract: The Filter API
  14. 3D WebGL
      Extract: WebGL 3D 
  15. 2D WebGL
    Extract: WebGL Convolutions 

<ASIN:1871962625>

<ASIN:B07XJQDS4Z>

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

pythondata

 



 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Monday, 22 February 2021 )