Table of Contents
jquery code
Home Web Front-end H5 Tutorial HTML5 practice - gray picture gallery implementation method

HTML5 practice - gray picture gallery implementation method

Mar 23, 2017 pm 04:06 PM

In the past, if you wanted to display grayscale images on the web, you had to manually convert them using image software. But now this process can be achieved with the help of html5canvas, without the need to use image editing software. I made a demo using html5 and jquery to show how to implement this function.

Purpose

This demo will show you how to use HTML5 and jquery to realize the transition between the grayscale image and the original image when the mouse moves out of the image. switch. Before the emergence of HTML5, to implement this function, you needed to prepare two images, one grayscale image and one original image. But now it can be achieved faster and easier with the help of HTML5, because the grayscale image is generated directly on the original image. I hope this js code will be helpful when you create a file or image display function.

Rendering

jquery code

The jquery code below will find the target image and generate a Grayscale version. When you move your mouse over the image, the grayscale image changes to primary color.

<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">    
    // 设置 window load事件是为了等待所有图片加载完毕之后才行运行
    $(window).load(function(){        
        // 使图片渐入,这样有颜色的原图就不会显示出来了,然后再执行window load 事件
        $(".item img").fadeIn(500);        
        // 复制图片
        $(&#39;.item img&#39;).each(function(){            
        var el = $(this);
            el.css({"position":"absolute"}).wrap("<p class=&#39;img_wrapper&#39; 
            style=&#39;display: inline-block&#39;>").clone().addClass(&#39;img_grayscale&#39;)
            .css({"position":"absolute","z-index":"998","opacity":"0"}).insertBefore(el).queue(function(){                
            var el = $(this);
                el.parent().css({"width":this.width,"height":this.height});
                el.dequeue();
            });            
            this.src = grayscale(this.src);
        });        
        // 使图片渐入 
        $(&#39;.item img&#39;).mouseover(function(){
            $(this).parent().find(&#39;img:first&#39;).stop().animate({opacity:1}, 1000);
        })
        $(&#39;.img_grayscale&#39;).mouseout(function(){
            $(this).stop().animate({opacity:0}, 1000);
        });        
    });    
    // 使用canvas制作灰色图片
    function grayscale(src){        
    var canvas = document.createElement(&#39;canvas&#39;);        
    var ctx = canvas.getContext(&#39;2d&#39;);        
    var imgObj = new Image();
        imgObj.src = src;
        canvas.width = imgObj.width;
        canvas.height = imgObj.height; 
        ctx.drawImage(imgObj, 0, 0); 
        var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);        
        for(var y = 0; y < imgPixels.height; y++){            
        for(var x = 0; x < imgPixels.width; x++){                
        var i = (y * 4) * imgPixels.width + x * 4;                
        var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg; 
                imgPixels.data[i + 1] = avg; 
                imgPixels.data[i + 2] = avg;
            }
        }
        ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);        
        return canvas.toDataURL();
    }        
</script>
Copy after login

How to use

Follow the steps below:

Reference jquery.js

Copy the above code

Set the target image (eg: .post-img, img, .gallery img, etc.)

You can also set Speed ​​of animation (ie. 1000 = 1 second)

Compatibility

I tried them all Browsers that support html5 and canvas, such as Chrome, Safari, and Firefox. If it is a browser that does not support HTML5, it will only use the original image and will not generate a grayscale image.

Note: If the local html file cannot run on firefox and chrome, you need to deploy the html file to the server.

Self-Practice

I tested it myself according to the tutorial and found some things that need attention. I used firefox to open the page. The program did not run correctly, but the relevant code was deployed. It can be run after reaching the server.

It must be a local image, otherwise a Security error will be reported.

This is because:

Canvas is a canvas element in the HTML5 standard and can be used to draw 2D and 3D images.

But it is easy to encounter Security when debugging error problem.

Currently, the Security errors I have encountered during debugging mainly appear in toDataURL() and src.

Security error indicates that this code has no semantic problems. But it cannot run normally due to security reasons.

Throw Security error:

  1. Using cross-domain images in Canvas

  2. Debugging in a local serverless environment

  3. Unable to obtain the relationship between the current domain and the image

Found on stackoverflow Some solutions usually allow you to solve cross-domain problems.

But in fact, this problem will also occur if you do not use server software when debugging locally.

For example: use the toDataURL function when debugging locally , local image files are used in Canvas at this time. Security errors will still be thrown in Chrome and Firefox.

The common solution is to set up a server environment locally, or submit the content to Debug again on the server.

The above is the detailed content of HTML5 practice - gray picture gallery implementation method. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

See all articles