search
HomeWeb Front-endH5 TutorialHTML5组件Canvas实现图像灰度化(步骤+实例效果)

HTML5组件Canvas实现图像灰度化(步骤+实例效果)

新建一个html页面,在body tag之间加入 

<canvas id="myCanvas" >Gray Filter</canvas>

添加一段最简单的JavaScript 脚本 

<pre name="code" class="javascript">window.onload = function() { 
var canvas = document.getElementById("myCanvas"); 
<span style="white-space:pre"> </span>// TODO: do something here 
}

从Canvas对象获取绘制对象上下文Context的代码如下: 

var context = canvas.getContext("2d");
在html页面中加入一幅图像的html代码如下
<img id="imageSource" src="hanjiaren.jpg" alt="Canvas Source" />
从html img对象中获取image 对象的javascript代码如下:
var image = document.getElementById("imageSource");
将得到的图像绘制在Canvas对象中的代码如下: 
context.drawImage(image, 0, 0);
从Canvas对象中获取图像像素数据的代码如下: 
var canvasData = context.getImageData(0, 0, canvas.width, canvas.height);
读取像素值与实现灰度计算的代码如下: 
for ( var x = 0; x < canvasData.width; x++) { 
for ( var y = 0; y < canvasData.height; y++) { 
// Index of the pixel in the array 
var idx = (x + y * canvasData.width) * 4; 
var r = canvasData.data[idx + 0]; 
var g = canvasData.data[idx + 1]; 
var b = canvasData.data[idx + 2]; 
// calculate gray scale value 
var gray = .299 * r + .587 * g + .114 * b; 
// assign gray scale value 
canvasData.data[idx + 0] = gray; // Red channel 
canvasData.data[idx + 1] = gray; // Green channel 
canvasData.data[idx + 2] = gray; // Blue channel 
canvasData.data[idx + 3] = 255; // Alpha channel 
// add black border 
if(x < 8 || y < 8 || x > (canvasData.width - 8) || y > (canvasData.height - 8)) 
{ 
canvasData.data[idx + 0] = 0; 
canvasData.data[idx + 1] = 0; 
canvasData.data[idx + 2] = 0; 
} 
} 
}

其中计算灰度公式为 gray color = 0.299 × red color + 0.578 × green color + 0.114 * blue color 
读取出来的像素值顺序为RGBA 分别代表red color, green color, blue color, alpha channel 

处理完成的数据要重新载入到Canvas中。代码如下: 
context.putImageData(canvasData, 0, 0); 
程序最终的效果如下: 

1006.jpg

完全源代码如下: 

 
 
<script> 
window.onload = function() { 
var canvas = document.getElementById("myCanvas"); 
var image = document.getElementById(&quot;imageSource&quot;); 
// re-size the canvas deminsion 
canvas.width = image.width; 
canvas.height = image.height; 
// get 2D render object 
var context = canvas.getContext(&quot;2d&quot;); 
context.drawImage(image, 0, 0); 
var canvasData = context.getImageData(0, 0, canvas.width, canvas.height); 
alert(canvasData.width.toString()); 
alert(canvasData.height.toString()); 
// gray filter 
for ( var x = 0; x &lt; canvasData.width; x++) { 
for ( var y = 0; y &lt; canvasData.height; y++) { 
// Index of the pixel in the array 
var idx = (x + y * canvasData.width) * 4; 
var r = canvasData.data[idx + 0]; 
var g = canvasData.data[idx + 1]; 
var b = canvasData.data[idx + 2]; 
// calculate gray scale value 
var gray = .299 * r + .587 * g + .114 * b; 
// assign gray scale value 
canvasData.data[idx + 0] = gray; // Red channel 
canvasData.data[idx + 1] = gray; // Green channel 
canvasData.data[idx + 2] = gray; // Blue channel 
canvasData.data[idx + 3] = 255; // Alpha channel 
// add black border 
if(x &lt; 8 || y &lt; 8 || x &gt; (canvasData.width - 8) || y &gt; (canvasData.height - 8)) 
{ 
canvasData.data[idx + 0] = 0; 
canvasData.data[idx + 1] = 0; 
canvasData.data[idx + 2] = 0; 
} 
} 
} 
context.putImageData(canvasData, 0, 0); // at coords 0,0 
}; 
</script> 
 
 

Hello World!

<img id="imageSource" src="hanjiaren.jpg" alt="Canvas Source" /> <canvas id="myCanvas" >Gray Filter</canvas>

代码中的文件可以替换任意你想要看到的图片文件 
HTML5, 原来如此神奇。程序在google浏览器中测试通过, 
最后的忠告,千万不要在本地尝试运行上面的代码,google浏览器的安全检查会自动阻止从浏览器中读写非domain的文件 
最好在tomcat或者任意个web container的server上发布以后从google浏览器查看效果即可。


以上就是HTML5组件Canvas实现图像灰度化(步骤+实例效果)的内容,更多相关内容请关注PHP中文网(www.php.cn)!



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
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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