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); // 复制图片 $('.item img').each(function(){ var el = $(this); el.css({"position":"absolute"}).wrap("<p class='img_wrapper' style='display: inline-block'>").clone().addClass('img_grayscale') .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); }); // 使图片渐入 $('.item img').mouseover(function(){ $(this).parent().find('img:first').stop().animate({opacity:1}, 1000); }) $('.img_grayscale').mouseout(function(){ $(this).stop().animate({opacity:0}, 1000); }); }); // 使用canvas制作灰色图片 function grayscale(src){ var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); 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>
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:
Using cross-domain images in Canvas
Debugging in a local serverless environment
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!

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
