网络科技

    今日:340| 主题:245428
收藏本版
互联网、科技极客的综合动态。

[其他] Getting Started With Paper.js: Projects and Items

[复制链接]
火钳刘明 发表于 2016-10-4 19:38:20
70 3

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
You may or may not have heard of    Paper.js. So, let's begin with the question: what is Paper.js? It is a library that allows you to create and work with vector graphics. The official website describes it as the Swiss Army Knife of Vector Graphics Scripting.   
  Despite the fact that the library has a lot to offer, it is easy to learn even if you have never heard of it before. In this tutorial I will begin with the very basics of the library and then move on to complex topics later.
  Using PaperScript

  There are two ways to use the library. You can use PaperScript, which is an extension of JavaScript, and help get things done a bit more quickly, or you can just use plain old JavaScript.
  PaperScript is just the same old JavaScript that you have always been using. However, it adds support for mathematical operators for    pointand    sizeobjects. It also simplifies the installation of event handlers for     Project,    View, and mouse    Toolobjects.   
  When loading PaperScript, you have to use the usual script tag with type set to "text/paperscript". If you are loading the code externally, you also need to add a    <script>tag with the appropriate URL to load your code. One last attribute that you need to specify is    data-paper-canvas="canvasId", or the shorthand version     canvas="canvasId", which tells the library about the canvas that it needs to work on. The code below creates a quadrilateral in PaperScript.  
  1. <script type="text/paperscript" canvas="quad">
  2.   var path = new Path();
  3.   path.strokeColor = 'black';
  4.   var pointOne     = new Point(100, 20);
  5.   var pointTwo     = new Point(-100, 100);
  6.   var pointThree   = new Point(300, 30);
  7.   path.moveTo(pointOne);
  8.   path.lineTo(pointOne + pointTwo);
  9.   path.lineTo(pointTwo + pointThree);
  10.   path.lineTo(pointOne + pointThree);
  11.   path.closed = true;
  12. </script>
复制代码
Using JavaScript

  If you are not comfortable with PaperScript, you can also use JavaScript in your projects. You will have to add a few more lines of code if you decide to do it this way. The first thing that you need to do is check if the DOM is ready because you won't be able to work with the canvas before that. After that you can set up a project and a view using the    paperobject. All the Paper.js classes and objects will now be accessible only through the    paperobject.   
  As I pointed out earlier, you will have to use Math functions instead of operators when working with Point and Size. The code below illustrates all these differences:
  1. window.onload = function() {
  2.   var canvas = document.getElementById('quad');
  3.   paper.setup(canvas);
  4.   var path = new paper.Path();
  5.   path.strokeColor = 'black';
  6.   var pointOne     = new paper.Point(100, 20);
  7.   var pointTwo     = new paper.Point(-100, 100);
  8.   var pointThree   = new paper.Point(300, 30);
  9.   path.moveTo(pointOne);
  10.   path.lineTo(pointOne.add(pointTwo));
  11.   path.lineTo(pointTwo.add(pointThree));
  12.   path.lineTo(pointOne.add(pointThree));
  13.   path.closed = true;
  14.   paper.view.draw();
  15. }
复制代码
As evident from the code snippets above, it is relatively easy to use PaperScript when working with Paper.js. Therefore, all the examples from now on will be based on PaperScript.
  Project Hierarchy

  If you have ever used a graphic design application like Adobe Photoshop or Illustrator, you must be familiar with the concept of layers. Each layer in these programs has its own content which, when combined with other layers, creates the final result. Similar layers also exist in Paper.js and can be accessed using    project.layers.   
  Initially, every project has a single layer which is accessible through    project.activeLayer. Any new items that you create are added to the currently active layer as its child. All the children in a specific layer can be accessed using the    layer.childrenproperty of the active layer.  
  There are multiple ways to access all these children. If you only need access to the first and last child of any item, you can use    item.firstChildand    item.lastChildrespectively. You can also assign a specific name to any child and then use that name to access it later. Let's say a layer you are working on has about 30 children. It is not practical to go over all of them one by one. For this reason, the library has a     layer.children.lengthproperty which you can use to get the total number of children and then iterate over the list using a    forloop.   
  This code snippet accesses various children using all the properties we just discussed:
  1. var circleA = new Path.Circle(new Point(45, 150), 45);
  2. var circleB = new Path.Circle(new Point(110, 150), 20);
  3. var circleC = new Path.Circle(new Point(165, 150), 35);
  4. var circleD = new Path.Circle(new Point(255, 150), 55);
  5. var circleE = new Path.Circle(new Point(375, 150), 65);
  6. var circleF = new Path.Circle(new Point(475, 150), 35);
  7. circleC.name = 'GreenCircle';
  8. project.activeLayer.firstChild.fillColor = 'orange';
  9. project.activeLayer.lastChild.fillColor = 'pink';
  10. project.activeLayer.children[1].fillColor = 'purple';
  11. project.activeLayer.children['GreenCircle'].fillColor = 'lightgreen';
  12. for (var i = 3; i < 5; i++) {
  13.   project.activeLayer.children[i].fillColor = 'tomato';
  14. }
复制代码
The embedded    demobelow shows the script in action. You can verify that the color of all circles matches the color that we assigned to them in the code above.  
  You can also use the    item.parentmethod to access the parent of an item, like the    item.childrenmethod, which you used to access all its children. Whenever you create a new item, its parent will always be the currently active layer of the project. However, it can be changed by adding the item as a child of another    layeror    group.   
  Before going any further, let me explain what a    groupactually is. To be honest, both    layerand    groupare very similar. One major difference between these two is that any new items that you create are automatically added to the active layer, but in the case of a group, you will have to add the items yourself.   
  There are multiple ways in which you can add items to a group. You can pass an item of arrays to the group constructor and they will all be added to the group's    item.childrenarray. To add elements to a group once it has been created, you can use the    item.addChild(item)function. You can also insert a child at a specific index using the    item.insertChild(index, item)function.   
  Removing items is also just as easy as adding them. To remove any item from a project, you can use the    item.remove()function. Keep in mind that this won't destroy the item, and it can be added back to the project any time you want. If the item you removed had any children, all of the children will be removed as well. What if you want to remove all the children but keep the item intact? This can be achieved by using the    item.removeChildren()function.  
  Understanding Items

  The term    itemhas appeared more than a few times in the tutorial now. So, what is it? Everything that appears within a Paper.js project is an    item. This includes    layers,    paths,    groups, etc. While different items have properties that are specific to them, other properties are applicable to all of them.  
  If you intend to hide an item from the user, you can do so by setting the value    item.visibleto    false. You can also clone any item using the    item.clone()function. This function returns the cloned item, which you can store in a variable and manipulate later. You can also change the opacity of any item using the    item.opacityproperty. Any value between 0 and 1 will make the item translucent.  
  You can also set a blend mode for any item using the    item.blendModeproperty. The blend mode needs to be passed as a    string. The library also provides an    item.selectedproperty which, if set to    true, creates a visual outline on top of that element. This can be pretty useful during debugging as it allows you to see the construction of paths, individual segment points, and bounding boxes of items.  
  Item Transformations

  Items can be scaled, rotated or moved around in a Paper.js project with ease. In this section, I will cover all these transformations briefly.
  To change the position of an    item, you can use its    item.positionproperty and set the position to a new point. If you want to move an element around, you can do so with the help of the     +=operator.  
  You can also scale any item by using the    item.scale(scale)function. This will scale the item around its center point. You can scale an item around some other point by specifying it as a second parameter, like    item.scale(scale, point). Moreover, the library also allows you to scale items differently in vertical and horizontal directions by passing two numbers as parameters, like    item.scale(scaleX, scaleY).  
  Rotating items is similar to scaling them. You can use the    item.rotate(angle)function to rotate elements around their center. The angle is specified in degrees, and rotation occurs in a clockwise direction. To rotate an item around a specific point, you can also pass a point as a second parameter, like     item.rotate(angle, point).   
  The following code snippet applies all the transformations and manipulations that we just discussed on three different rectangles.
  1. var rectA = new Path.Rectangle(new Point(250, 70), new Size(120, 120));
  2. rectA.fillColor = 'pink';

  3. var rectB = rectA.clone();
  4. rectB.fillColor = 'purple';
  5. rectB.position += new Point(80, 80);
  6. rectB.opacity = 0.6;
  7. rectB.blendMode = 'color-burn';
  8. rectB.scale(1.5);
  9. rectB.rotate(45);

  10. var rectC = rectB.clone();
  11. rectC.fillColor = 'lightgreen';
  12. rectC.position += new Point(-180, 0);
  13. rectC.blendMode = 'color-dodge';
  14. rectC.scale(1.5);
复制代码
The code is pretty much self-explanatory. I clone rectangle B from rectangle A, and rectangle B acquires all properties of rectangle A. The same goes for rectangle B and C.
  Note that I have used the    +=operator that I discussed above to move the items around. This operator moves items relative their old positions instead of using absolute values.  
  The demo below shows you the final result after all these transformations. You can try out different blend-modes or change other properties    in the demoto see how they affect the final result.  
  Final Thoughts

  As I mentioned earlier, Paper.js is easy to learn and allows you to create vector graphics with ease. This tutorial covered the very basics that you need to know to work with the library. Soon, we will publish the next tutorial of the series, which will discuss paths and geometry in detail.
  In the meantime, it's important to note that JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the    Envato marketplace.  
  Until then, I suggest that you create a few basic demos of our own and practise what you have learned so far. If you have any questions regarding this tutorial, let me know in the comments.
友荐云推荐




上一篇:流媒体视频网络 Tout 获 2600 万美元 C 轮融资,“大鲨鱼”奥尼尔当顾问 ...
下一篇:How to Manage Files and Use the File System on Android
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

千与千寻 发表于 2016-10-4 21:32:55
大家有什么看法,赶快说说
回复 支持 反对

使用道具 举报

厌倦了゛ 发表于 2016-10-4 21:49:33
幸福毕竟不是曹操,怎能说到就到。
回复 支持 反对

使用道具 举报

a03669 发表于 2016-10-4 22:18:43
打酱油的人拉,回复下赚取积分
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表