JavaScript >> Javascript 文檔 >  >> jQuery

使用類似 Instagram 的過濾器製作 Web 應用程序

在本教程中,我們將製作一個簡單的網絡應用程序,允許您將照片從計算機拖到瀏覽器窗口中,並在其上應用類似 Instagram 的過濾器。為此,我們將使用一些 JavaScript 庫和插件:

  • Caman.js - 這是一個功能強大的畫布操作庫,可讓您在圖像上應用各種效果和濾鏡。它帶有 18 個預設過濾器,我們將在此示例中使用它們(您可以根據需要創建更多);
  • Filereader.js - 這是一個圍繞 HTML5 拖放事件的輕量級包裝器,使它們更易於使用。它還為 jQuery 添加了一個方法,因此您可以將事件綁定到特定元素;
  • jQuery Mousewheel - 我正在使用這個插件來滾動過濾器容器;
  • 此外,在撰寫本文時,我們使用的是最新版本的 jQuery。

還要非常感謝 Jenn 和 Tony Bot 提供的照片。

HTML

第一步是編寫示例的HTML:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />

    <title>Instagram-like Filters with jQuery | Tutorialzine Demo</title>
    <link href="assets/css/style.css" rel="stylesheet" />

    <!-- Include the Yanone Kaffeesatz font -->
    <link href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400,200" rel="stylesheet" />

</head>
<body>

    <h1>Instagram <b>Filters</b></h1>
    <div id="photo"></div>

    <div id="filterContainer">
        <ul id="filters">
            <li> <a href="#" id="normal">Normal</a> </li>
            <li> <a href="#" id="vintage">Vintage</a> </li>
            <li> <a href="#" id="lomo">Lomo</a> </li>
            <li> <a href="#" id="clarity">Clarity</a> </li>
            <li> <a href="#" id="sinCity">Sin City</a> </li>
            <!-- 14 More filters go here -->
        </ul>
    </div>

    <!-- Libraries -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="assets/js/filereader.min.js"></script>
    <script src="assets/js/caman.full.js"></script>
    <script src="assets/js/jquery.mousewheel.min.js"></script>
    <script src="assets/js/script.js"></script>

</body>
</html>

除了介紹中提到的庫之外,我還包括了 script.js 文件,它承載了我們稍後將要編寫的代碼。在頭部部分,我包含了來自 Google Web Fonts 的 Yanone Kaffeesatz 字體。

JavaScript/jQuery

為了使應用程序正常運行,我們必須執行以下操作:

  1. 接受 拖放圖像;
  2. 創建 一個新的畫布元素(原始),最大尺寸為 500x500 像素(可自定義)並將其保存在內存中;
  3. 點擊過濾器。選擇一個時:
    • 創建原始畫布的克隆;
    • 移除頁面上當前的所有畫布元素;
    • 將克隆附加到#photo div;
    • 如果所選過濾器與“普通”過濾器不同,請調用 Caman 庫。否則什麼都不做;
    • 將所選過濾器標記為“活動”類。
  4. 觸發器 “正常”過濾器。

現在我們知道要做什麼了,讓我們開始編碼吧!

資產/js/script.js

$(function() {

    var maxWidth = 500,
        maxHeight = 500,
        photo = $('#photo'),
        originalCanvas = null,
        filters = $('#filters li a'),
        filterContainer = $('#filterContainer');

    // Use the fileReader plugin to listen for
    // file drag and drop on the photo div:

    photo.fileReaderJS({
        on:{
            load: function(e, file){

                // An image has been dropped.

                var img = $('<img>').appendTo(photo),
                    imgWidth, newWidth,
                    imgHeight, newHeight,
                    ratio;

                // Remove canvas elements left on the page
                // from previous image drag/drops.

                photo.find('canvas').remove();
                filters.removeClass('active');

                // When the image is loaded successfully,
                // we can find out its width/height:

                img.load(function() {

                    imgWidth  = this.width;
                    imgHeight = this.height;

                    // Calculate the new image dimensions, so they fit
                    // inside the maxWidth x maxHeight bounding box

                    if (imgWidth >= maxWidth || imgHeight >= maxHeight) {

                        // The image is too large,
                        // resize it to fit a 500x500 square!

                        if (imgWidth > imgHeight) {

                            // Wide
                            ratio = imgWidth / maxWidth;
                            newWidth = maxWidth;
                            newHeight = imgHeight / ratio;

                        } else {

                            // Tall or square
                            ratio = imgHeight / maxHeight;
                            newHeight = maxHeight;
                            newWidth = imgWidth / ratio;

                        }

                    } else {
                        newHeight = imgHeight;
                        newWidth = imgWidth;
                    }

                    // Create the original canvas.

                    originalCanvas = $('<canvas>');
                    var originalContext = originalCanvas[0].getContext('2d');

                    // Set the attributes for centering the canvas

                    originalCanvas.attr({
                        width: newWidth,
                        height: newHeight
                    }).css({
                        marginTop: -newHeight/2,
                        marginLeft: -newWidth/2
                    });

                    // Draw the dropped image to the canvas
                    // with the new dimensions
                    originalContext.drawImage(this, 0, 0, newWidth, newHeight);

                    // We don't need this any more
                    img.remove();

                    filterContainer.fadeIn();

                    // Trigger the default "normal" filter
                    filters.first().click();
                });

                // Set the src of the img, which will
                // trigger the load event when done:

                img.attr('src', e.target.result);
            },

            beforestart: function(file){

                // Accept only images.
                // Returning false will reject the file.

                return /^image/.test(file.type);
            }
        }
    });

    // Listen for clicks on the filters

    filters.click(function(e){

        e.preventDefault();

        var f = $(this);

        if(f.is('.active')){
            // Apply filters only once
            return false;
        }

        filters.removeClass('active');
        f.addClass('active');

        // Clone the canvas
        var clone = originalCanvas.clone();

        // Clone the image stored in the canvas as well
        clone[0].getContext('2d').drawImage(originalCanvas[0],0,0);

        // Add the clone to the page and trigger
        // the Caman library on it

        photo.html(clone);

        var effect = $.trim(f[0].id);

        Caman(clone[0], function () {

            // If such an effect exists, use it:

            if( effect in this){
                this[effect]();
                this.render();
            }
        });

    });

    // Use the mousewheel plugin to scroll
    // scroll the div more intuitively

    filterContainer.find('ul').on('mousewheel',function(e, delta){

        this.scrollLeft -= (delta * 50);
        e.preventDefault();

    });

});

此示例適用於所有支持文件拖放的瀏覽器。一些過濾器是計算密集型的,所以在結果顯示在屏幕上之前你會有點滯後。為了加快速度,我將圖像的最大寬度/高度限制為 500 像素,但您可以根據自己的喜好更改這些值。

完成!

將此示例與我們的 Photobooth 教程結合起來會很酷,並最終在您的瀏覽器中創建一個真正的類似 Instagram 的應用程序。但我將把它留給讀者作為練習:)


Tutorial JavaScript 教程
  1. 如何讓瀏覽器導航到 JavaScript 中的 URL

  2. 帶有 React Hooks 的 JavaScript 計時器

  3. 回歸基礎:JavaScript 運算符、條件和函數

  4. 箭頭函數:關於轉換的練習測驗

  5. 如何成長為開發人員?

  6. 減速器:令人困惑但方便

  7. 在瀏覽器 Javascript 和 Tailwind 中生成條形碼

  1. 反應滾動處理程序鉤子

  2. 使用 Vue 3、VueUse 和 CSS 的鼠標跟踪眼睛

  3. 如何在簡單的 React Carousel 中顯示多個項目

  4. 從綠色到紅色取決於百分比

  5. 合理預期原則

  6. 最佳發布/訂閱消息代理

  7. 為站點編程 注意 我們正在準備食物

  1. 如何編寫 IMMUTABLE 代碼並且永遠不會再次陷入調試

  2. 類似博客的帖子、滾動動畫、動作引用 |模塊星期一 41

  3. CI/CD 流水線實踐 | AWS 代碼管道、Elastic Beanstalk、GitHub

  4. 2022 年 4 個必須知道的 JavaScript 框架