JavaScript Canvas - Fetch API
Written by Ian Elliot   
Tuesday, 16 July 2024
Article Index
JavaScript Canvas - Fetch API
Working with the Server - Basic Fetch
Request Object

Request Object

Things are only a little more complicated when you want to do something more than just a get. You can specify a second parameter, the init object, in the call to control the type of request made.

The init object has lots of properties, but the most important are:

  • method – the request method e.g. GET, POST, PUT etc

  • headers – a header object

  • body – the body of the request which is sent to the server, which can be any of Blob, BufferSource, FormData, URLSearchParams, USVString or ReadableStream. You can find the full specification in the documentation.

If you want to repeatedly fetch the same resource it is better to create a Request object which has all of the properties of the init object plus a URL property. You can pass the Request object to fetch in place of the URL parameter and it acts as the init object as well.

So the previous fetch could be implemented as:

async function getText(){ 
	var request=new Request(’myFile.txt’,
            		       	{
		                   method:’GET’
}); var response=await fetch(request);

Notice that you can reuse a Request object even if you have streamed the body data of its associated Response. However, as already commented, you cannot reuse a Response object after you have read its body data.

You can also obtain a duplicate Request or Response object using the clone method. This can be useful if you aren’t sure that the response will be valid. For example, to first check to see if the response is valid json we could use:

var response = await fetch(request);
var res2 = response.clone();
try{
	console.log(await res2.json());
   } catch (e) {
	console.log(await response.text());
   }

If the response isn’t valid json it is displayed as text. Notice you have to clone the response before trying to retrieve the body. You cannot clone a stream that has been read.

You can use a fluent style to make this look neater:

var response = await fetch(request);
try{
	console.log(await response.clone().json());
   }
catch (e) {
	console.log(await response.text());
   }

The clone method introduces a buffer into the equation and the data is streamed into a local buffer from where it can be accessed a second time. This has the side effect of keeping the data in memory until all of the copies are read or disposed of.

Downloading Graphics from the Server

Using fetch this is very easy. All you need is a call to fetch with the correct URL and then use one of the formatted reads to get the data. The problem is that there is no format provided that works simply with graphics data.

You can read the file as a blob but then you have to create an object URL, read the data into an Image object and draw to the canvas. For example:

async function fetchGraphic(url){
    var response=await fetch(url);
    var blob=await response.blob();
    return new Promise(
                  function (resolve, reject) {
                     var url = URL.createObjectURL(blob);
                     var img = new Image();
                     img.addEventListener("load",
function (e) { resolve(img); URL.revokeObjectURL(url); }, false); img.src = url; }); }

The only advantage of this overloading of the URL directly into the Image object is that the load occurs with the fetch rather than on setting the src attribute.

In fact the more direct:

async function fetchGraphic2(url) {
  return new Promise(
                 function (resolve, reject) {
                    var img = new Image();
                    img.addEventListener("load",
function (e) { resolve(img); }, false); img.src = url; }); }

is also slightly faster because we don’t have to load the file and then load the blob into the Image object.

Notice that this doesn’t mean that fetch is useless as, while it isn’t the best way to load graphics, it is completely general and it also works with upload. Sometimes we need to load the file as an array to do some work on it before using it as a graphic, see the PCX example at the end of the next chapter.

In Chapter but not in this extract

  • Uploading Local Graphics
  • Using FormData
  • 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: SVG 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
      Extract: OffscreenCanvas
  10. Bit Manipulation In JavaScript
      Extract: Bit Manipulation
  11. Typed Arrays
      Extract: Typed Arrays 
  12. Files, blobs, URLs & Fetch
      Extract: Blobs & Files
      Extract: Read/Writing Local Files
      Extract: Fetch API **NEW!
  13. Image Processing
      Extract: ImageData
      Extract:The Filter API
  14. 3D WebGL
      Extract: WebGL 3D
  15. 2D WebGL
    Extract: WebGL Convolutions

<ASIN:B07XJQDS4Z>

<ASIN:1871962579>

<ASIN:1871962560>

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.

espbook

 

Comments




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



Last Updated ( Wednesday, 17 July 2024 )