This article mainly introduces canvas learning and filter implementation code. Using canvas, front-end personnel can easily perform image processing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.
In this era of proliferation of digital products, taking pictures has become an indispensable part of life. Whether at home, outing, or traveling long distances, you will always take some beautiful photos. But the photos taken directly by the camera often have a certain gap between them and our psychological expectations. So how to reduce this gap? The answer is beauty P-pictures, so all kinds of beauty cameras are popping up, and P-pictures have become a portable skill.
In fact, the so-called beauty is just the use of many filters, and filters use certain algorithms to manipulate picture pixels to obtain some special image effects. Friends who have used Photoshop know that there are a lot of filters in PS. Below we will use js canvas technology to achieve several filter effects.
I recently learned the highlight of HTML5 - canvas
. Using canvas, front-end personnel can easily perform image processing. There are many APIs. This time I mainly study the commonly used APIs and complete the following two codes:
implementation of decolorization filter
implementation of negative Color (inverse color) filter
1 Do you know canvas?
1.1 What is canvas?
This HTML element is designed for client-side vector graphics. It has no behavior of its own, but exposes a drawing API to client JavaScript so that the script can draw whatever it wants to a canvas.
1.2 What is the difference between canvas, svg and vml?
<canvas></canvas>
An important difference between markup and SVG and VML is that <canvas></canvas>
has a JavaScript-based drawing API , while SVG and VML use an XML document to describe the drawing.
2 canvas drawing learning
Most Canvas drawing APIs are not defined on the <canvas></canvas>
element itself , but defined on a "drawing environment" object obtained through the getContext()
method of the canvas. The default width and height of the <canvas></canvas>
element itself are 300px and 150px respectively.
2.1 canvas draws a rectangle
// 处理canvas元素 var c = document.querySelector("#my-canvas"); c.width = 150; c.height = 70; // 获取 指定canvas标签 上的context对象 var ctx = c.getContext("2d"); ctx.fillStyle = "#FF0000"; // 颜色 ctx.fillRect(0, 0, 150, 75); // 形状
2.2 canvas draws a path
var c = document.querySelector("#my-canvas"); var ctx = c.getContext("2d"); ctx.moveTo(0, 0); // 开始坐标 ctx.lineTo(200, 100); // 结束坐标 ctx.stroke(); // 立即绘制
2.3 canvas draws a circle
For the ctx.arc()
interface, the five parameters are: (x,y,r,start,stop)
. Among them, x and y are the coordinates of the center of the circle, and r is the radius.
The units of start
and stop
are radians. Not length, not °.
var c = document.querySelector("#my-canvas"); var ctx = c.getContext("2d"); ctx.beginPath(); ctx.arc(95, 50, 40, 0, 2 * Math.PI); ctx.stroke();
2.4 canvas drawing text
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.font = "30px Arial"; ctx.fillText("Hello World", 10, 50);
3 canvas image processing learning
3.1 Commonly used API interfaces
There are four main APIs for image processing:
Drawing images: drawImage(img,x,y,width,height)
or drawImage(img,sx,sy,swidth,sheight,x,y,width,height)
Get image data: getImageData(x,y,width,height )
Rewrite image data: putImageData(imgData,x,y[,dirtyX,dirtyY,dirtyWidth,dirtyHeight])
Export image: toDataURL([type, encoderOptions])
For more detailed API and parameter descriptions, please see: canvas image processing API parameter explanation
3.2 Drawing images
Based on these APIs, we can draw our pictures in the canvas
element. Suppose our picture is ./img/photo.jpg
.
<script> window.onload = function () { var img = new Image() // 声明新的Image对象 img.src = "./img/photo.jpg" // 图片加载后 img.onload = function () { var canvas = document.querySelector("#my-canvas"); var ctx = canvas.getContext("2d"); // 根据image大小,指定canvas大小 canvas.width = img.width canvas.height = img.height // 绘制图像 ctx.drawImage(img, 0, 0, canvas.width, canvas.height) } } </script>
As shown below, the picture is drawn into the canvas:
4 Implement the filter
Here we mainly borrow the getImageData
function, which returns the RGBA value of each pixel. With the help of image processing formulas, you can manipulate pixels to perform corresponding mathematical operations.
4.1 Color removal effect
The color removal effect is equivalent to the black and white photos taken by old cameras. Based on the sensitivity of the human eye, people have given the following formula:
gray = red * 0.3 green * 0.59 blue * 0.11
The code is as follows:
<script> window.onload = function () { var img = new Image() img.src = "./img/photo.jpg" img.onload = function () { var canvas = document.querySelector("#my-canvas"); var ctx = canvas.getContext("2d"); canvas.width = img.width canvas.height = img.height ctx.drawImage(img, 0, 0, canvas.width, canvas.height) // 开始滤镜处理 var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var i = 0; i < imgData.data.length / 4; ++i) { var red = imgData.data[i * 4], green = imgData.data[i * 4 + 1], blue = imgData.data[i * 4 + 2]; var gray = 0.3 * red + 0.59 * green + 0.11 * blue; // 计算gray // 刷新RGB,注意: // imgData.data[i * 4 + 3]存放的是alpha,不需要改动 imgData.data[i * 4] = gray; imgData.data[i * 4 + 1] = gray; imgData.data[i * 4 + 2] = gray; } ctx.putImageData(imgData, 0, 0); // 重写图像数据 } } </script>
The effect is as shown below:
4.2 Negative color effect
The negative color effect is to subtract the current value from the maximum value value. The theoretical maximum numerical value in RGB obtained by getImageData is: 255. Therefore, the formula is as follows:
new_val = 255 - val
The code is as follows:
<script> window.onload = function () { var img = new Image() img.src = "./img/photo.jpg" img.onload = function () { var canvas = document.querySelector("#my-canvas"); var ctx = canvas.getContext("2d"); canvas.width = img.width canvas.height = img.height ctx.drawImage(img, 0, 0, canvas.width, canvas.height) // 开始滤镜处理 var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var i = 0; i < imgData.data.length / 4; ++i) { var red = imgData.data[i * 4], green = imgData.data[i * 4 + 1], blue = imgData.data[i * 4 + 2]; // 刷新RGB,注意: // imgData.data[i * 4 + 3]存放的是alpha,不需要改动 imgData.data[i * 4] = 255 - imgData.data[i * 4]; imgData.data[i * 4 + 1] = 255 - imgData.data[i * 4 + 1]; imgData.data[i * 4 + 2] = 255 - imgData.data[i * 4 + 2]; } ctx.putImageData(imgData, 0, 0); // 重写图像数据 } } </script>
The rendering is as follows:
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit Html5 Video Tutorial!
Related recommendations:
php public welfare training video tutorial
The above is the detailed content of Canvas learning and filter implementation code. For more information, please follow other related articles on the PHP Chinese website!

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.


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

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

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.

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use
