网络科技

今日:340| 主题:245428

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

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.
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:
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);
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.

 大家有什么看法，赶快说说

 幸福毕竟不是曹操，怎能说到就到。

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

• 双十二优化好详情页不要再让转化率拖后腿了

紧跟着就是双12亲亲节，圣诞节，元旦节，年货节 [...]

• 其实我只对你这样 微信背景图片

我以为，你只对我这样，其实你对所有人也这样 [...]

• 微商不仅会P图 他们还P视频！马云无辜躺枪

要论P图造假， 小编只服各路微商， 无论是虚假聊 [...]

• 雇佣水军相互绞杀 谁强谁被黑 这是互联网金

互金行业正处在黎明前最深的黑暗——监管 [...]

• 创业一年被拒217次，从卖血维生到身家200亿

文/金错刀频道Max（微信公号：金错刀） 上周， [...]

• 看过来，卖家你要的爆款在这里

今天要分享的是我自己的爆款实操经验，所以要进 [...]

• 华为人均工资高达58万！不过请你先看看华为

最近一直在研究华为2015年的年报，今天发 [...]

• Millions in US still living life in Inte

Elliott Brown Millions of Ame [...]

• 刘成城对话柳传志：为了钱而创业，和卖宅基

今日，由36氪主办的“WISE·2016独角兽峰会 [...]

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