Table of Contents
Basic knowledge of animation
Image Basics
光栅化项目
最终想法
Home CMS Tutorial WordPress Getting Started with Paper.js: Animations and Images

Getting Started with Paper.js: Animations and Images

Sep 03, 2023 am 09:05 AM
Getting Started Guide paperjs animations 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);
}
Copy after login

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;
}
Copy after login

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. <​​/p> <图>

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;
});
Copy after login

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

<图>

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

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

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

<图>

光栅化项目

虽然 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);
Copy after login

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

最终想法

如果您已阅读本系列中的所有教程,您应该拥有足够的知识来开始使用 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 of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A Beginner's Guide to Natural Language Processing in PHP A Beginner's Guide to Natural Language Processing in PHP Jun 11, 2023 pm 06:30 PM

With the development of artificial intelligence technology, Natural Language Processing (NLP) has become a very important technology. NLP can help us better understand and analyze human language to achieve some automated tasks, such as intelligent customer service, sentiment analysis, machine translation, etc. In this article, we will cover the basics and tools for natural language processing using PHP. What is natural language processing? Natural language processing is a method that uses artificial intelligence technology to process

Getting Started with PHP: PATCH Requests and Responses Getting Started with PHP: PATCH Requests and Responses May 23, 2023 pm 04:21 PM

As the Internet continues to develop, the demand for front-end and back-end technologies is also increasing. As a back-end developer, mastering PHP is essential. In PHP development, we often need to process requests and responses. This article will discuss the PATCH request and response, providing a practical guide for PHP beginners. 1. PATCH request The PATCH request is an HTTP request method, which is used to update existing resources. In the HTTP protocol, there is a way to use a PUT request to

Beginner's Guide to Java Development: From Getting Started to Giving Up Beginner's Guide to Java Development: From Getting Started to Giving Up Sep 22, 2023 am 08:25 AM

Java is a programming language widely used in software development. Its concise syntax and powerful functions make it the first choice for many developers. However, for beginners, learning Java may feel a little difficult. This article will provide a guide for Java development beginners to help them from getting started to giving up. Learn basic syntax. The basic syntax of Java includes variables, data types, operators, conditional statements, loop statements, etc. Beginners should start with these basic concepts and write simple code examples to deepen their understanding.

Getting Started with PHP: PHP and YAML Getting Started with PHP: PHP and YAML May 20, 2023 pm 08:21 PM

PHP is a popular server-side scripting language commonly used for web development, while YAML is a lightweight data serialization format used for configuration files and data exchange. In this article, we'll explore how PHP works with YAML and how to get started. PHP and YAML When developing web applications, developers need to deal with a large amount of data and configuration. These data and configurations can be stored in a database or using text files. Text files usually use XML, JSON or YA

PHP Beginner's Guide: Parsing Taobao Product Details API Document PHP Beginner's Guide: Parsing Taobao Product Details API Document Jun 30, 2023 pm 06:22 PM

Introduction to PHP Technology: Taobao Product Details API Document Interpretation Introduction: PHP, as a programming language widely used in Web development, has a large user group and a rich extension library. Among them, using PHP to develop Taobao product details API is a very practical and common requirement. This article will provide a detailed interpretation of the Taobao product details API document to provide an introductory guide for beginners. 1. What is Taobao Product Details API? Taobao Product Details API is an interface provided by Taobao open platform.

Starting from scratch: PHP WebSocket development introductory guide and function implementation tutorial Starting from scratch: PHP WebSocket development introductory guide and function implementation tutorial Sep 12, 2023 am 10:51 AM

Starting from scratch: PHP WebSocket development introductory guide and function implementation tutorial 1. Introduction With the development of the Internet, the demand for real-time communication is increasing. As a new real-time communication protocol, WebSocket has gradually attracted the attention and use of developers. This article will use PHP as the development language to introduce the basic concepts of WebSocket, and provide an introductory development guide suitable for beginners to help readers implement WebSocket functions from scratch. 2. WebSocket

Getting Started with PHP: Code Refactoring Getting Started with PHP: Code Refactoring May 26, 2023 pm 04:21 PM

Refactoring is a very important process when writing PHP code. As an application grows, the code base becomes larger and harder to read and maintain. Refactoring is to solve this problem and make the code more modular and better organized and extensible. When we refactor the code, we need to consider the following aspects: Code style Code style is a very important point. Keeping your coding style consistent will make your code easier to read and maintain. Please follow PHP coding standards and be consistent. Try using a code style checking tool such as PHP

Beginner's Guide to PHP Image Processing Beginner's Guide to PHP Image Processing Jun 11, 2023 am 08:49 AM

PHP is a very popular server-side programming language and it is widely used for web development. In web development, image processing is a very common requirement, and it is also very simple to implement image processing in PHP. This article will briefly introduce the introductory guide to PHP image processing. 1. Environmental requirements To use PHP image processing, you first need the support of the PHPGD library. The library provides functionality for writing images to files or outputting them to a browser, cropping and scaling images, adding text, and making images grayscale or inverting. therefore

See all articles