search
HomeCMS TutorialWordPressGetting Started with Paper.js: Animations and Images

Getting Started with Paper.js: Animations and Images

Sep 03, 2023 am 09:05 AM
Getting Started Guidepaperjsanimations and images

So far in this series, I've covered items and items, paths and geometry, and user interaction in Paper.js. The library also allows you to animate various items in your project. If you combine this with the ability to act based on user input, you can create some really cool effects. This tutorial shows you how to animate items in Paper.js.

Later in this tutorial we will also cover image processing and how to manipulate the color of individual pixels. The library also enables you to create rasters from vectors, which will be covered at the end.

Basic knowledge of animation

All animations in Paper.js are handled by the onFrame event handler. Code within the handler is executed up to 60 times per second. The view is automatically redrawn after each execution. Gradually changing some properties inside a function can create some very nice effects.

The

onFrame handler also receives an event object. This object has three properties that provide us with animation-related information.

The first one is event.count, which tells us the number of times the handler has been executed. The second one is event.delta which gives us the total time elapsed since the last time the handler was executed. The third one is event.time which gives us the time elapsed since the first frame event.

You can animate many properties in a handler. In our example, I'll rotate three rectangles and change the tint of the center rectangle. Consider the following code:

var rectA = new Path.Rectangle({
  point: [300, 100],
  size: [200, 150],
  strokeColor: 'yellow',
  strokeWidth: 10
});

var rectB = rectA.clone();
rectB.strokeColor = 'orange';
rectB.scale(0.8);
var rectC = rectA.clone();
rectC.strokeColor = 'black';
rectC.scale(1.2);

function onFrame(event) {
  rectA.strokeColor.hue += 10 * event.delta;
  rectA.rotate(2);
  rectB.rotate(2);
  rectC.rotate(2);
}

As is evident from the above code snippet, very little actual code is required to animate a rectangle. For rectangle A, we increase the tint by a factor of 10 event.delta each time the onFrame handler is executed. The value of event.delta is generally close to 0.01. If I hadn't multiplied its value by 10, it would have taken a long time to notice the change in color.

Every time I execute the code, I rotate each rectangle by 2 degrees. If we use the value event.time to rotate the rectangle, the rotation will become very fast after a while.

#You can also animate individual fragments instead of animating the entire path or item at once. The process itself is very simple. You can use path.segments to return an array of all the segments that make up the path. Individual segments can be accessed by providing the index value. Before going any further, I'd like you to take a look at the code below.

var aSquare = new Path.RegularPolygon(new Point(550, 200), 4, 100);
aSquare.fillColor = 'pink';
aSquare.fullySelected = true;

function onFrame(event) {
  for (var i = 0; i <= 3; i++) {
    var sinValue = Math.sin(event.time * 4 + i);
    
    aSquare.segments[i].point.x = sinValue * 100 + 350;
  }
  aSquare.segments[1].point.y = sinValue * 50 + 100;
}

Here, we first create a square using the Path.RegularPolygon(center, Sides, radius) constructor. sides The parameter determines the number of sides of the polygon. radius The parameter determines the size of the polygon. I also set the completelySelected property to true so you can see the individual points.

Within the onFrame handler, I use a for loop to iterate over all the segments and set their x-coordinates equal to the values ​​calculated based on their indexes. Using the event.time function inside the Math.sin() function will not create any problems related to extreme values, because the value of Math.sin() will not create Any problem related to extreme values. The sin() function will always lie between -1 and 1.

The following demo shows our animated square, which by the way is no longer a square thanks to the code in our onFrame handler. I suggest you try different values ​​for the polygon constructor as well as the arguments to the sin function to see how they affect the final animation in the demo.

Image Basics

Images in Paper.js are called rasters. You can transform and move them like any other item. To use an image in your project, you first have to add it to the markup of your web page using the usual img tag and assign it an id. This id is then passed to the new Raster(id) constructor.

Remember that the image you are using needs to be loaded and should be hosted on the same website as your project. Using images hosted on other domains will result in security errors. In this tutorial we will manipulate the following images:

Getting Started with Paper.js: Animations and Images

要访问上图中各个像素的颜色,您可以使用 栅格。 getPixel(x, y) 函数,其中 x 和 y 是像素的坐标。下面的代码生成 7*7 像素的正方形,填充位于左上角的像素的颜色:

var raster = new Raster('landscape');
var gridSize = 8;
var rectSize = 7;

raster.on('load', function() {  
  raster.size = new Size(80, 40);

  for (var y = 0; y < raster.height; y++) {
    for (var x = 0; x < raster.width; x++) {
      
      var color = raster.getPixel(x, y);
      var path = new Path.Rectangle( new Point(x, y) * gridSize, new Size(rectSize, rectSize));

      path.fillColor = color;
    }
  }

  project.activeLayer.position = view.center;
});

加载栅格后,我们将其大小调整为 80*40。像素。在嵌套的 for 循环内,我们遍历该栅格的各个像素并创建 7*7 的正方形。增加栅格的大小会给我们带来更好的结果,但执行速度会更慢。这是最终结果,调整后的光栅在左上角可见:

如果要隐藏调整大小后的栅格,可以将 raster.visible 属性设置为 false。您还可以操纵生成的方块的颜色。例如,要增加所有方块中的红色分量,您可以使用以下行:

path.fillColor = color + new Color(0.4,0,0);

在这种情况下,最终结果将是:

光栅化项目

虽然 Paper.js 是一个矢量图形库,但它还允许您从现有项目创建光栅。为此,您必须使用 item.rasterize() 方法。光栅化后,原始项目本身不会从项目中删除。您还可以选择指定光栅的分辨率(以每英寸像素为单位)。下面的代码以不同的分辨率从多边形创建两个栅格:

var aDodecagon = new Path.RegularPolygon(new Point(150, 180), 12, 30);
aDodecagon.fillColor = '#CCAAFC';
  
var dodecRasterA = aDodecagon.rasterize();
dodecRasterA.position.x += 250;
  
var dodecRasterB = aDodecagon.rasterize(150);
dodecRasterB.position.x += 500;
  
aDodecagon.scale(3);
dodecRasterA.scale(3);
dodecRasterB.scale(3);

与中间的相比,最右边的分辨率更高的多边形仍然很清晰。最终结果如下:

最终想法

如果您已阅读本系列中的所有教程,您应该拥有足够的知识来开始使用 Paper.js。虽然学习该库的基础知识很容易,但掌握所有概念将需要您付出一些努力。每当您需要有关某个主题的更多信息时,您可以浏览官方网站上的参考资料。

JavaScript 已成为事实上的网络工作语言之一。它并非没有学习曲线,而且还有大量的框架和库可以让您忙碌起来。如果您正在寻找其他资源来学习或在工作中使用,请查看我们在 Envato 市场中提供的资源。

如果您使用此库创建了一些有趣的东西,请在评论中分享您的作品。

The above is the detailed content of Getting Started with Paper.js: Animations and Images. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Can I learn WordPress in 3 days?Can I learn WordPress in 3 days?Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

Is WordPress a CMS?Is WordPress a CMS?Apr 08, 2025 am 12:02 AM

WordPress is a Content Management System (CMS). It provides content management, user management, themes and plug-in capabilities to support the creation and management of website content. Its working principle includes database management, template systems and plug-in architecture, suitable for a variety of needs from blogs to corporate websites.

What is the WordPress good for?What is the WordPress good for?Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Should I use Wix or WordPress?Should I use Wix or WordPress?Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

How much does WordPress cost?How much does WordPress cost?Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Is WordPress still free?Is WordPress still free?Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

Is WordPress easy for beginners?Is WordPress easy for beginners?Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress?Why would anyone use WordPress?Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),