Processing. js tutorials and processing tutorials for javascript developers

Source: Internet
Author: User

Processing. js tutorials and processing tutorials for javascript developers

This tutorial is intended for javascript developers. Before reading this document, you 'd better master javascript and web development programming, and have basic Processing knowledge.
Directory:
Prepare for those who have no patience to read the long story:
If you are anxious to get started, you need to know the following points:
1. Processing. js converts the Processing code into javascript code that can be run on the browser. In essence, the <canvas> label is used for plotting;
2. to use it, you first download Processing. js;
3. Create Your Processing file with the extension name ". PVDF", which is the same as a common text file that you normally create, for example: hello-web.pde
4. Create an html page and reference Processing inside and outside the page. add a <canvas> label on the <canvas> label that specifies your sketch file (as the name suggests, the sketch file is the Processing file ), A sketch file can have multiple files separated by spaces. For example:

<script src="processing-1.3.6.min.js"></script> <canvas data-processing-sources="hello-web.pde"></canvas> 

When loading your web page, processing. js will parse and translate the sketch file, and then your sketch file will run in the browser.
Source of Processing. js?
What is Processing?

The Processing language was originally created by MIT as part of the multimedia lab and Aesthetics & computer group. With Processing, software developers, artists, and data visualization engineers can be connected, and programmers and non-programmers can easily be competent for visualization. Processing is created in java. You can think of it as a simplified java with simplified APIs for painting and drawing.
What can Processing do on the web end?
Processing has a large and active community group that specializes in creating 2D and 3D images, visualized data suites, audios, videos, and more. Because HTML5 and web terminals have canvas, audio, and video functions, which were originally available only through flash and java Plug-ins. At the same time, the advanced javascript Engine enables javascript to be fully competent for previously very slow tasks.
By porting the Processing language to the web end, both Processing and web community will benefit. For Processing, this means that the source code can not only work on the desktop, but also run on the browser. For the web community, a new and mature image programming language that is close to full functionality was born. <Canvas> elements are too low-level for programmers who directly use interfaces provided by javascript, so more advanced libraries are necessary. Processing. js can be treated as a library that simplifies operations on 2D and 3Dcanvas.
How much work is required to learn processing
The Processing language is small and complete, so it is very easy to learn. This document not only attempts to teach you Processing, but also encourages you to look for standard tutorials, books, and examples of Processing. Any Processing code or concepts should be mapped to Processing. js (unless listed below ). You can skip the java syntax javascript in favor of Processing and use pure javascript to use it together with Processing's drawing API.
Processing
The original intention of Processing. js is to enable Processing developers and Processing code (usually sketches) to run on the web without modification. Therefore, the recommended method is to use Processing. js to write the processing code, convert it to javascript through Processing. js, and then run it.
Over time, some web developers began to use processing. js, And they demanded that the designed API be used out of the Processing language. Therefore, we provide a method that can be developed in pure javascript language and can use Processing methods and objects. Note: Processing. js is the top priority, and is the most important part of Processing open to the web. It has the right to decide whether it is compatible with Processing. It is not designed as a general HTML Image Library. It has been said that it can be used as a canvas advanced drawing API.
Next we will discuss the various Processing. js methods used in web pages.
Write pure Processing code
This method is the preferred method to use Processing. js, and has been introduced in a long article in Processing. js for Processing Devs quick start guide. Summary:
1. Download processing. js
2. Create a separate Processing file or multiple files. The name can be called at will, as long as the suffix is ". De.
3. Create a web page including Processing. js and <canvas> labels. The <canvas> information contains the path of the sketch file (s) and the list of Procesing file names separated by spaces, and these list names are placed on the canvas attribute data-processing-sources. For example:

 <!DOCTYPE html>  

When the page is loaded (on page load), processing. js will automatically browse the document on the web page to search for the data-processing-sources attribute of the <canvas>, and then use XMLHTTPRequest to download these files and stuff them into the translator from porcessing to javascript, the translated javascript code will be executed through the eval function.
Pre-compiled processing code is javascript
Processing. js automatically downloads and converts all Processing code into javascript. It does this using the Processing. compile () method, and the related processing build tools or utilities can do the same thing.
To obtain the compiled code from the Processing code (for example, JavaScript is applicable to processing. js), follow these steps:

 // hard-coded Processing code, text from an HTML widget, downloaded text, etc. var processingCode = "..."; var jsCode = Processing.compile(processingCode).sourceCode; 

For example, the following Processing code will generate the compiled javascript code under it:

// Processing code  void setup() {  size(200, 200);  background(100);  stroke(255);  ellipse(50, 50, 25, 25);  println("hello web!"); }   // "Comiled" JavaScript code  // this code was autogenerated from PJS  (function(processing, $constants) {  function setup() {  processing.size(200, 200);  processing.background(100);  processing.stroke(255);  processing.ellipse(50, 50, 25, 25);  processing.println("hello web!");  }  processing.setup = setup;  }) 

Write the processing. js code of javascrui only.
The previous method generates javascript code for processing, but you can also write javascript separately. The Parser of processing. js converts the Processing code into a javascript method and then runs it. Therefore, it is entirely possible to skip the Processing code, write only the javascript method, and pass the method to a Processing instance. Here is an example:

function sketchProc(processing) {  // Override draw function, by default it will be called 60 times per second  processing.draw = function() {   // determine center and max clock arm length   var centerX = processing.width / 2, centerY = processing.height / 2;   var maxArmLength = Math.min(centerX, centerY);    function drawArm(position, lengthScale, weight) {   processing.strokeWeight(weight);   processing.line(centerX, centerY,    centerX + Math.sin(position * 2 * Math.PI) * lengthScale * maxArmLength,    centerY - Math.cos(position * 2 * Math.PI) * lengthScale * maxArmLength);   }    // erase background   processing.background(224);    var now = new Date();    // Moving hours arm by small increments   var hoursPosition = (now.getHours() % 12 + now.getMinutes() / 60) / 12;  drawArm(hoursPosition, 0.5, 5);    // Moving minutes arm by small increments   var minutesPosition = (now.getMinutes() + now.getSeconds() / 60) / 60;   drawArm(minutesPosition, 0.80, 3);    // Moving hour arm by second increments   var secondsPosition = now.getSeconds() / 60;   drawArm(secondsPosition, 0.90, 1);  }; }  var canvas = document.getElementById("canvas1"); // attaching the sketchProc function to the canvas var processingInstance = new Processing(canvas, sketchProc); 

A sketch method is created here, which is the same as the code generated by the parser. This method requires a parameter, which is a reference to a Processing object (for example, a processing runtime object) generated by the Processing constructor, any Procesing method or object is accessed as its attribute.
Once this method is completed and passed, a reference points to the canvas and a reference points to the Processing Constructor (remember to use "new ").
Write a file that combines Processing and javascript.
The first question that people often ask is whether processing. js can read values from files running Processing sketch. Or vice versa. The answer is yes.
Processing. js converts Processing code into a javascript code containing function closures. All the variables and methods you created are not bound to the global variables (that is, window ). However, you can still access them.
1) access javascript objects from Processing
All Processing code is converted to javascript and run like other functions. This means that you can create a variable or method in the global script module, and they can be automatically accessed by Processing. Consider the following example:
The first is the Processing file, mixed. PVDF:

 String processingString = "Hello from Processing!";   void setup() {  printMessage(jsString + " " + processingString); } 

Next is the web page:

<!DOCTYPE html> 

The variables and method declarations allowed by Processing. js are outside the Processing code.
2) javascript and Processing code Mixing
In the previous example, javascript and processing code are placed in separate files, and the boundaries between them are not very close.
Because Processing. js may also directly mix them together when converting code. Processing. the javascript parser keeps the javascript contained in the Processing code unchanged, so that developers can write the mixed code of processing and javascript (Note: This is why processing. js does not use the pure processing parser ). This is an example that was previously written using this method:

var jsString = "Hello from JavaScript!"; var printMessage = function(msg) {  document.getElementById('msg').innerHTML = "Message: " + msg;  };   String processingString = "Hello from Processing!";   void setup() {  printMessage(jsString + " " + processingString);  } 

Some javascript syntaxes are hard to be written together in this way (for example, regular syntax ). If that is the case, you can simply move the pure javasript code to a <script> code block and access it as described in "Accessing JavaScript Objects from Processing" above.
3) Access processing from javascript
The conclusion is that accessing javascript from the Processing code is much easier than the other way around, because the javascript created by the Processing parser is not directly exposed to the global object, so you can only use Processing. instances attributes.
The constructor of Processing constantly monitors instance creation and allows them to use the getInstanceById () method. By default, when <canvas> has the data-processing-source attribute, its id will be the unique identifier of the Processing instance. If you do not have the id attribute, you can use Proessing. instance [0] for access.
When you have a reference that can access the Processing instance, you can call it like this:

<!DOCTYPE html> 

There are two buttons in the DOM structure that are used to allow the user to start or pause the running Processing sketch.
They directly control the Processing instances in javascript (You may have multiple instances on the page or hide them in the div) by calling the Processing Methods: loop () and noLoop (). These Processing methods can be found in other files.
As a must-know thing for developers who use Processing. js:
When Processing. js tries to be fully compatible with Processing, there are some different things or solutions. We have also added some web specification functions to make Processing easier to use. Here are some tips that may be helpful when you start to use Processing. js for complicated sketch.
Processing. js provides the "externals" attribute to access various DOM/javascript objects.
Each Processing instance (Processing. instances) contains an "external" attribute, which is an object that contains various DOM/javascritp objects that point to very useful non-Processing, such:

Canvas -- canvas context bound to sketch -- execution context onblur and onfocus -- event Processor

If a division expression is expected to generate an integer value, this may require explicit conversion.
When the Processing code is converted to javascript and involves the division of integer and floating point types, a bug occurs in the class.
In the Processing code, there is a code block for dividing something directly by integers. When it is converted to Processing, there may be some problems, because an integer Programming Dual-precision type is introduced into a decimal part. The method to fix this bug is to explicitly convert any division, as shown in:

 // before int g = mouseX / i;  // after  int g = (int)(mouseX / i); 

Processing. js has a spoofing mechanism for simulating asynchronous input and output of Processing.
Processing uses a model for synchronizing input and output, which means that execution takes a relatively long time like the loadImage () method, but nothing happens during their execution, the program waits until loadImage () is executed to execute the next statement. This means that the value returned by methods such as loadImage () can be used in the subsequent code.
However, this is not the case in a web browser. It uses an asynchronous input/output model, which means that the method for loading external resources cannot wait until they are loaded before execution. To implement the Processing load method, you have to use a special Processing command.
The Processing. js command prompts the browser that the command is written in the comment instead of the Processing code. This is a typical Processing sketch. It needs to load an image synchronously and draw it:

PImage img;  void setup() { img = loadImage("picture.jpg");  image(img, 0, 0);  } 

The code will not be executed in a browser containing Processing. js, because the image file picture.jpg is called before it is loaded. The method to fix this bug is to load the image and cache it before the execution of the sketch, that is, the pre-loading technology. Here is the modified Code:

/* @pjs preload="picture.jpg"; */ PImage img; void setup() { img = loadImage("picture.jpg"); image(img, 0, 0);  } 

Note: additional comment lines placed at the top of the Code. The "@ jps" command is used for Processjing. js, not for developers. It can be considered as an additional line of code, which will be executed before the program is executed.
If you have multiple images loaded, you can use the following list:

/* @pjs preload="picture.jpg,picture2.jpg,picture3.png"; */ 

Processing. js requires more attention on variable naming than Processing
One of the most powerful features of javascript is its dynamic and weak nature. Because java is a strongly-typed language, Processing is also the same. They can name them repeatedly without being afraid of ambiguity (for example, method overloading), and Processing. js won't work. Cannot enter the internal work of javascript, so for Processing. js developers, the best advice is not to use function/class/etc/or name variables from Processing. For example, a variable named line may look reasonable, but it may cause problems because it is the same as Processing and the built-in function name line () of Procesing. js.
Processing requires your help to override the overloaded parent class method.
If your code uses a subclass to overwrite the overloaded methods in one or more parent classes, you need to overwrite them with "false" because you have not changed each method signature:

class X {  void doSomething() {  ...  }   void doSomething(float x, float y)  {  ...  }  } class Y extends X  {  void doSomething() {  // different code from compared to the super class }   // even though we don't override this method, // its signature must be added to prevent Pjs  // from getting the method chain wrong:  void doSomething(float x, float y)  {  super.doSomething(x,y);  }  } 

Although you do not need to implement the empty doSomething method with (float, float) Signatures in Processing, this is almost necessary to ensure Processing. js is not dizzy when calling methods.
It is also possible to directly put the Processing code in the web page.
On the canvas, it is the first choice to use a data-processing-source attribute to include external files loaded by Processing. js. However, it is recommended to reference scripts inside and outside the web page. However, writing a row Reference is also acceptable.
The code in the above example is used as a reference in the line. It is necessary to modify the Code as follows:

<script src="processing-1.3.6.min.js"></script> <script type="application/processing" data-processing-target="pjs"> void setup() { size(200, 200); background(100); stroke(255); ellipse(50, 50, 25, 25); println('hello web!'); } </script> <canvas id="pjs"> </canvas>

The code is more complicated because it does not point out the canvas with the script file (that is, you can reference multiple Processing sketch on a page, or you can have multiple canvas ). The "type" attribute of the script is not described. This attribute is used to differentiate javascript and Processing code (the browser will ignore the Processing script ). Note: The "id" and "target" attributes are used to connect the Processing script and related canvas.

The above is all the content in this article. I hope you will have some knowledge about Processing. js.

Articles you may be interested in:
  • VML drawing board ② script-VMLgraph. js and XMLtool. js
  • Drawing with js
  • Drawing with JavaScript -- JS2D function set
  • JavaScript drawing code
  • Use JavaScript code to unlock a mobile device drawing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.