search
HomeWeb Front-endJS TutorialDevelop image editing tools with CamanJS: Explore layers, blending modes, and event handling

使用 CamanJS 开发图像编辑工具:探索图层、混合模式和事件处理

In the previous tutorial, you learned how to use CamanJS to create an image editor that can apply basic filters such as contrast, brightness, and noise to images. CamanJS also has some other built-in filters like nostalgia, pinhole, sunrise, etc. that we apply directly to the image.

In this tutorial, we will introduce some of the more advanced features of the library, such as layers, blend modes, and events.

Layers in CamanJS

In this first tutorial, we only use a single layer containing the image. All filters we apply only manipulate this main layer. CamanJS allows you to create multiple layers so that you can edit images in more complex ways. You can create nested layers, but they will always be applied to their parent layer like a stack.

Whenever you create a new layer and apply it to a parent layer, the default blending mode used will be normal. You can create a new layer on the canvas using the newLayer() method. When you create a new layer, you can also pass a callback function, which can be useful if you plan to manipulate the layer.

This function can be used for many tasks, such as setting the blending mode of a new layer using the setBlendingMode() method. Likewise, you can control the opacity of the new layer using the opacity() method.

Any new layer you create can be filled with a solid color using the fillColor() method. You can also use the copyParent() method to copy the contents of a parent layer to a new layer. All the filters we learned in the previous tutorial can also be applied to the new layer we are creating. For example, you can increase the brightness of a newly created layer using this.filter.brightness(10).

You can also choose to load any other image in the layer and overlay it on the parent, rather than copying the parent or filling the layer with a solid color. Just like the main image, you can also apply different filters to the overlay image.

In the code snippet below, we attach a click event handler to three buttons that will fill the new layer with a solid color, the parent layer, and the overlay image respectively.

$('#orange-btn').on('click', function (e) {
    Caman("#canvas", function () {
        this.newLayer(function () {
            this.opacity(50);
            this.fillColor('#ff9900');
        });
        this.render();
    });
});

$('#parent-btn').on('click', function (e) {
    Caman("#canvas", function () {
        this.newLayer(function () {
            this.opacity(50);
            this.copyParent();
            this.filter.brightness(20);
        });
        this.render();
    });
});

$('#overlay-btn').on('click', function (e) {
    var oImg = new Image();
    oImg.src = "trees.png";
    
    Caman("#canvas", function () {
        this.newLayer(function () {
            this.opacity(50);
            this.overlayImage(oImg);
            this.filter.brightness(20);
        });
        this.render();
    });
});

Mixed Mode in CamanJS

In the previous section we kept the opacity below 100 for any new layers we added to the canvas. This is done because the new layer will completely hide the old layer. When you place one layer on top of another, CamanJS allows you to specify a blending mode that determines the final result after placement. The blending mode is set to normal by default.

This means that any new layer you add to the canvas will make the layers beneath it invisible. There are ten blending modes in this library. These are Normal, Multiplication, Screen, Overlay, Difference, Add, Exclude, softLight, Exclude and Darken.

As I mentioned before, the normal blending mode sets the final color equal to the color of the new layer. multiply The blending mode determines the final color of the pixel by multiplying the individual channels and then dividing the result by 255. Differences between multiply and addition Blend modes work similarly, but they subtract and add channels.

darken Blending mode sets the final color of a pixel equal to the lowest value of each color channel. lighten Blending modes set the final color of a pixel equal to the highest value of each color channel. The exclusion blending mode is somewhat similar to difference, but it sets the contrast to a lower value. In the case of the screen blending mode, the final color is obtained by inverting the colors of each layer, multiplying, and then inverting the result again.

If the bottom color is darker, the overlay blending mode works like multiply; if the bottom color is lighter, it works like screen.

CamanJS also allows you to define your own blending modes if you want colors in different layers to interact differently. We'll cover this in the next tutorial in this series.

Here is the JavaScript code to apply different blending modes on the image:

$('#multiply-btn').on('click', function (e) {
    hexColor = $("#hex-color").val();
    Caman("#canvas", function () {
        this.revert(false);
        this.newLayer(function () {
            this.fillColor(hexColor);
            this.setBlendingMode('multiply');
        });
        this.render();
    });
});

$('#screen-btn').on('click', function (e) {
    hexColor = $("#hex-color").val();
    Caman("#canvas", function () {
        this.revert(false);
        this.newLayer(function () {
            this.fillColor(hexColor);
            this.setBlendingMode('screen');
        });
        this.render();
    });
});

In the above code snippet, we get the hexadecimal color value from the input field. Then apply that color to a new layer. You can write code to apply other blending modes in a similar manner.

尝试在输入字段中指定您选择的颜色,然后通过单击相应的按钮应用任何混合模式。在示例中,我已将混合模式应用于纯色,但您也可以将它们应用于上一节中的重叠图像。

CamanJS 中的事件

如果您在第一个教程或第二个教程的演示中上传了任何大图像,您可能会注意到,任何应用的滤镜或混合模式的结果在很长一段时间后变得明显。

大图像具有大量像素,在应用特定混合模式后计算每个像素的不同通道的最终值可能非常耗时。例如,当对尺寸为 1920*1080 的图像应用 multiply 混合模式时,设备必须执行超过 600 万次乘法和除法。

在这种情况下,您可以使用事件向用户提供有关滤镜或混合模式进度的一些指示。 CamanJS 有五个不同的事件,可用于在不同阶段执行特定的回调函数。这五个事件是 processStartprocessCompleterenderFinishedblockStartedblockFinished

processStartprocessComplete 事件在单个过滤器开始或完成其渲染过程后触发。当您指定的所有过滤器都已应用于图像时,库将触发 renderFinished 事件。

CamanJS 在开始操作之前将大图像分成块。 blockStartedblockFinished 事件在库处理完图像的各个块后触发。

在我们的示例中,我们将仅使用 processStartrenderFinished 事件来通知用户图像编辑操作的进度。

Caman.Event.listen("processStart", function (process) {
    $(".process-message").text('Applying ' + process.name);
});
Caman.Event.listen("renderFinished", function () {
    $(".process-message").text("Done!");
});

通过 processStartprocessFinish 事件,您可以访问当前在图像上运行的进程的名称。另一方面,blockStartedblockFinished 事件使您可以访问块总数、当前正在处理的块以及已完成块的数量等信息。

尝试单击下面演示中的任何按钮,您将在画布下方的区域中看到当前操作图像的进程的名称。

最终想法

本系列的第一个教程向您展示了如何使用 CamanJS 库中的内置滤镜创建基本图像编辑器。本教程向您展示了如何处理多个图层以及如何对每个图层单独应用不同的滤镜和混合模式。

由于大图像的图像编辑过程可能需要一段时间,因此我们还学习了如何向用户表明图像编辑器实际上正在处理图像而不是闲置。

在本系列的下一个也是最后一个教程中,您将学习如何在 CamanJS 中创建自己的混合模式和滤镜。如果您对本教程有任何疑问,请随时在评论中告诉我。

The above is the detailed content of Develop image editing tools with CamanJS: Explore layers, blending modes, and event handling. 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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

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

Hot Tools

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),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.