Processing.js Introductory tutorials for JavaScript developers _javascript tips

Source: Internet
Author: User
Tags mixed processing instruction

This introductory guide is written for JavaScript developers. Before reading this document, you had better master JavaScript and Web development programming, and also very basic processing knowledge.
Directory:
prepare for people who don't have the patience to look at the long-winded:
         If you're in a hurry to get started, Then you need to know the following points:
             1, processing.js The processing code translates into JavaScript code that can be run on the browser side, essentially through the <canvas> tag to achieve the drawing;
              2, in order to use it, your first download processing.js;
              3, create your processing file with the suffix ". Pde", which is the same as normal text files that you normally create, such as: Hello-web.pde
              4, create an HTML page, then reference the Processing.js file inside and out of the page, and add a < Canvas> label, the <canvas> label indicates that you sketch file (as the name suggests, sketch file, is processing file), sketch file can have multiple files, multiple files separated by a space. For example:            

<script src= "Processing-1.3.6.min.js" ></script> 

Load your Web page, Processing.js will parse, translate sketch file, and your sketch file will run in the browser.
the source of processing.js?
What is processing?

The processing language was originally created by MIT as part of a multimedia lab and aesthetic & Computer group. With processing, the gap between software developers, artists, and data visualization engineers can be reached, and programmers and non programmers can be easily qualified for visualization. Processing is created in Java, and you can think of it as a simplified Java, with a simplified API for painting and drawing.
what can processing do on the Web side?
Processing has large and active community groups that specialize in creating 2D and 3D images, visual data kits, audio, video, and more. Because the Html5,web end has Canvas,audio,video, these are features that were previously available only through Flash and Java plug-ins. At the same time, the advanced JavaScript engine makes JavaScript perfectly competent for things that have been slow to do before.
By porting the processing language to the web side, processing and the web community will benefit. For processing, this means that the source code can not only work on the desktop, but also run in the browser. For the web community, a new, mature and nearly full-featured image programming language was born. <canvas> elements for programmers who directly use JavaScript-provided interfaces, these native interfaces are too low-level, so more advanced libraries are necessary. Processing.js can be considered as such a simplified operation of 2d and 3Dcanvas libraries.
Learn how to processing, how much work you need to do
Processing language is small and complete, so it is very easy to learn. This document not only tries to teach you processing, but also encourages you to look for processing tutorials, books and examples. Any processing code or concept should be mapped to the processing.js (except as listed below). You can skip the JavaScript of the processing Pro Java syntax and use pure JavaScript to work with the processing paint API.
How to use processing
Processing.js was created to allow processing developers and processing code (usually sketches) to run on the web without modification. Therefore, the recommended way is to write the processing code with Processing.js and then run it by Processing.js into JavaScript.
Over time, some Web developers are starting to use processing.js, and they are demanding that the API be designed out of the processing language. Therefore, we provide a way to develop in a pure JavaScript language, and we can use processing methods and objects. Note: Processing.js is in the first place and is the most important part of processing to the web, with design decisions that are conducive to compatibility with processing. It is not designed to be a general-purpose HTML drawing library. As has been said, it can be used as a canvas advanced drawing API.
Next we discuss the various processing.js methods used in Web pages.
Write Pure processing code
This notation is the preferred method of using processing.js and has been introduced in processing.js for processing devs Quick Start Guide. summed up as follows:
1, download Processing.js
2, create a separate processing file, or multiple files, name can be casually called, as long as the suffix name is ". Pde" on the line.
3, create a Web page, the page includes processing.js and <canvas> tag,<canvas> information contains sketch file (s) path and space-separated procesing file name list, And these list names are placed on the canvas property data-processing-sources. For example:

 <! DOCTYPE html> 
  
 

When the page is loaded (on page load), Processing.js will automatically browse the document of the Web page to find the <canvas> properties data-processing-sources, Then use the XMLHttpRequest to download the files, cram them into the translator from porcessing to JavaScript, and the translated JavaScript will be executed via the Eval function.
precompiled processing code for JavaScript
processing.js automatically downloads and turns all processing code into JavaScript. It does this by using the Processing.compile () method, and the relevant processing build tools or utilities can do the same thing.
To get the code compiled from the processing code (for example, JavaScript works for processing.js), use the following procedure:

 hard-coded processing code, text from an HTML widget, downloaded text, etc. 
var Processingcode = "..."; 

For example, converting the following processing code generates the compiled JavaScript code below it:

Processing Code 
 Void Setup () { 
 size); 
 Background (m); 
 Stroke (255); 
 Ellipse (a); 
 println ("Hello web!"); 
} 
 
 "Comiled" JavaScript code 
 //This code is autogenerated from PJS 
 (function (processing, $constants) { 
 fu Nction Setup () { 
 processing.size); 
 Processing.background (m); 
 Processing.stroke (255); 
 Processing.ellipse (a); 
 Processing.println ("Hello web!"); 
 } 
 Processing.setup = setup; 
 

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

function Sketchproc (processing) {//Override draw function, by default it'll be is called times per second process Ing.draw = function () {//Determine center and Max Clock Arm length var CenterX = processing.width/2, CenterY = P 
  ROCESSING.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 ()% + 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);

       Here is the creation of a sketch method that is the same as the code generated by the parser. This method requires a parameter, which is a reference to a processing object generated by the processing constructor (for example, processing Run-time object), and any Procesing method or object is accessed as a property of it.
Once this method completes and passes, with a reference pointing to canvas, a reference to the processing constructor (remember "new").
writes a processing and JavaScript-combined file
       The first question that people often ask is whether processing.js can read the values from the files that are running processing sketch. or the opposite view. The answer is yes.
       processing.js converts processing code into a closed-package JavaScript code containing functions. All the variables and methods you create are not bound to the global variable (that is, window). However, you can still visit them.
1), accessing JavaScript objects from processing
               translates from processing code to JavaScript and works like other functions, and all processing code can access global objects. This means that you can create a variable or method in a global scripting module that can be automatically accessed by processing. Consider an example of this:
First processing file, Mixed.pde:

 String processingstring = "Hello from processing!"; 
 
 void Setup () { 
 printmessage (jsstring + "" + processingstring); 

Next is the Web page:

<! DOCTYPE html> 
 
 

Here Processing.js the variables and methods that are allowed to be declared outside of the processing code.
2), JavaScript and processing code mix
The preceding example allows JavaScript and processing code to be placed separately in separate files when the boundaries between them are not very close.
Because Processing.js can also directly mix them directly when translating code. The Processing.js parser retains the JavaScript contained in the processing code, allowing developers to write mixed code for processing and JavaScript (note: That's why There is no reason to use a pure processing parser in processing.js. This is an example that was previously written in this way:

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 grammars are difficult to mix together in this way (for example, regular syntax). If that is the case, you can simply move the pure Javasript code into a <script> code block and access it as described in "Accessing JavaScript Objects from processing" above.
     3), accessing processing from JavaScript
               comes to the conclusion that it's much easier to access JavaScript from the processing code than the reverse. Because JavaScript created by the processing parser is not directly exposed to the global object, you can only access it through processing.instances properties. The
              processing constructors have been monitoring the creation of instances, and allows them to use the Getinstancebyid () method. By default, when <canvas> has attribute Data-processing-source, its ID will be the only recognized negative for the processing instance. If there is no id attribute, you can access it using proessing.instance[0.
              When you have a reference that can access the processing instance, You can call it like this:

<! DOCTYPE html>  

There are 2 buttons in the DOM structure, and they are used to allow the user to choose to start or pause a running processing sketch.
They control processing instances directly in JavaScript (you might have multiple in the page, or hidden in a div), by calling the processing method: Loop () and Noloop (). These processing methods can be found in other files.
What you need to know as a developer using processing.js:
when Processing.js tries to be completely compatible with processing, there are different things or solutions. We have also added some Web specification features to make processing easier to use. Here are some tips and hints that might help when you start using Processing.js to do complex sketch.
Processing.js provides access to various Dom/javascript objects through the "Externals" attribute
each processing instance (that is, processing.instances) contains a "external" property that is an object that contains various DOM/JAVASCRITP objects that point to very useful non-processing. For example:

Canvas--sketch the 
execution context 
onblur and onfocus--event handler for the artboard on the binding context--the artboard 

If a division expression expects to produce an integer value, then this may require an explicit conversion
when the processing code is translated into JavaScript, involving integral vs floating-point division, there is a bug class that can cause this problem.
In processing code, a block of code that is directly divided by an integer can sometimes cause problems when converted into processing, because the integer programming double is introduced into a decimal part. The way to fix this bug is to explicitly convert any division, as shown in the practice:

 Before 
int g = mousex/i; 
 
After 
 int g = (int) (mousex/i); 

Processing.js has a deception. Asynchronous input and output in analog processing
processing uses a model of synchronous input and output, which means that, like the LoadImage () method, it takes a relatively long time to execute, but when they execute, nothing happens, and the program waits until it LoadImage () execution to execute the next line of statements. This means that the value returned by a method such as LoadImage () is used in the next code.
But this is not the case with Web browsers, which use asynchronous input-output models, which means that methods that load external resources do not allow the program to wait until they have finished loading. In order to implement the processing load method, you have to use a special processing instruction.
Processing.js instruction prompts the browser, the instruction is written in the comment rather than processing the code itself. This is a typical processing sketch, which needs to load a picture synchronously and then draw it:

Pimage img; 
 
void Setup () { 
img = loadimage ("picture.jpg"); 
 Image (IMG, 0, 0); 
 

The code will not execute in a browser containing processing.js because the picture file picture.jpg is invoked before it is loaded. The way to fix this bug is to get the picture loaded before the sketch starts, and to cache it, which is what it says Preloading technology. This is the modified code:

* * @pjs preload= "picture.jpg"; * * 
pimage img; 

void Setup () { 
img = loadimage ("picture.jpg"); 
Image (IMG, 0, 0); 
 

Note: Extra comment lines placed at the top of the code. "@jps" instructions are for processjing.js, not for developers. You can think of it as an extra line of code that will be executed before the program executes.
If you have multiple pictures that are loaded, you can use the following list:

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

Processing.js need more attention on the naming of variables than processing
One of the most powerful features of JavaScript is its dynamic, weakly-typed nature. Because Java is a strongly typed language, so is processing, and they can repeat names without fear of ambiguity (for example, overloading of methods), Processing.js. Can't get into JavaScript, so for processing.js developers, the best advice is not to use function/class/etc/, or to name variables from processing names. For example, a variable called line may look reasonable, but it can cause problems because it is the same as the processing and procesing.js built-in function name line ().
Processing needs your help when you want to overwrite overloaded parent-class methods
If your code uses subclasses to overwrite overloaded methods in one or more parent classes, you need a "fake" overlay, because each method signature, you usually do not change:

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 is added to prevent Pjs 
 //from getting th E method chain wrong: 
 void dosomething (float x, float y) 
 { 
 super.dosomething (x,y); 
 } 
 

Although you do not need to implement an empty method dosomething that has a (float,float) signature in the processing, this is almost necessary to ensure that processing.js does not get dizzy when calling the method.
It's also possible to put processing code directly on a Web page.
On canvas, it is preferred to use an Data-processing-source property to include processing.js loaded external files, but the recommended way is to reference the script inside and outside the Web page. But it is also possible to write inline references.
Take the code in the top example as an inline reference, and make the necessary changes:

<script src= "Processing-1.3.6.min.js" ></script> 
<script type= "Application/processing" data-processing-target= "PJs" > 
void Setup () { 
size); 
Background (m); 
Stroke (255); 
Ellipse (a); 
println (' Hello web! '); 
} 
</script> 
<canvas id= "PJs" > </canvas>

The code is more complicated because it does not point to the canvas with that script file (that is, you can refer to multiple processing sketch on one page, as well as multiple canvas). There is also no description of the script's "type" attribute, which is used to distinguish between JavaScript and processing code (the browser ignores the processing script). Finally, note: the "id" and "target" properties are used to connect the processing script and the associated canvas.

The above is the entire content of this article, I hope you have some knowledge of processing.js.

Related Article

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.