


Use canvas to achieve a picture triangulation (LOW POLY) effect_javascript skills
I accidentally saw Ovilia using threejs to make a LOW POLY, which is the effect of plane triangulation of pictures. I thought it was amazing, so I spent some time trying it myself.
I haven’t used threejs much, so I just used the 2D drawing API of canvas to do it, because it seems that threejs cannot be used for this effect.
Go directly to the demo first: http://whxaxes.github.io/canvas-test/src/Funny-demo/lowpoly/index.html (You can also watch it on the mobile terminal, but because of the calculation The amount is relatively large, and it will take more time to calculate on a mobile device than on a PC)
To achieve this effect, you mainly need to triangulate the image and perform edge detection on the image. Of these two, the first uses the delaunay triangulation algorithm, and the second uses the sobel edge detection algorithm. It sounds very high-end, but both algorithms have corresponding open source components that can be used directly: ironwallaby's delaunay component and Miguel Mota's sobel component.
Of these two algorithms, sobel is better, but delaunay is a bit complicated. We can study it in the future. However, if you only want to create an effect at the moment, you can still use these components.
Now that the two most important components are in place, the rest is very simple:
First draw the image onto canvas:
canvas.width = (img.width > 800) ? 800 : img.width; canvas.height = img.height * canvas.width/img.width; ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
Then get the imgData of canvas, and then return the new imgData through sobel calculation
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); var newImgData = Sobel(imgData);
If we put newImgData on canvas, we will find that the color image becomes a grayscale image like this:
Since the Sobel component mentioned above is not very suitable for my usage, and the code is also inappropriate, I made appropriate modifications and optimizations, optimized the loop method, accelerated the calculation speed, and added a callback function. For details, please see the sobel.js file in the project github
When traversing imgData.data in the Sobel method, the callback function will be called, and the coordinate points with a color value greater than 40 (that is, the grayscale is above rgb(40,40,40)) will be recorded in the callback. Come down. Then randomly obtain a part of the edge points, and then add some random coordinates and the coordinate values of the four corners. In this way, we can get the coordinate points we need
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); // 收集色值大于40的边缘像素点 var collectors = []; Sobel(imgData , function(value , x , y){ if(value > 40){collectors.push([x , y]);} }); // 添加一些随机点 for(var i=0;i<300;i++){particles.push([Math.random()*canvas.width , Math.random()*canvas.height]);} // 添加随机边缘点,数量为边缘点数量除于50 var length = ~~(collectors.length/50), random; for(var l=0;l<length;l++){ random = (Math.random()*collectors.length)<<0; particles.push(collectors[random]); collectors.splice(random , 1); } // 添加四顶点坐标 particles.push([0,0] , [0,canvas.height] , [canvas.width,0] , [canvas.width,canvas.height]);
After obtaining the coordinate points, you can use the delaunay component to calculate and obtain the triangular coordinate array in the correct order. By connecting the points in these arrays, you can have the following effect:
Of course, the effect we want is not to connect lines, but to color-fill all triangles, that is, to obtain the three coordinates of the triangle, then calculate the coordinates of the center point, and then obtain the corresponding coordinates in imgData based on the center point coordinates RGB color value, and then fill it into the triangular area:
// 使用delaunay三角化获取三角坐标 var triangles = Delaunay.triangulate(particles); var x1,x2,x3,y1,y2,y3,cx,cy; for(var i=0;i < triangles.length; i+=3) { x1 = particles[triangles[i]][0]; x2 = particles[triangles[i+1]][0]; x3 = particles[triangles[i+2]][0]; y1 = particles[triangles[i]][1]; y2 = particles[triangles[i+1]][1]; y3 = particles[triangles[i+2]][1]; // 获取三角形中心点坐标 cx = ~~((x1 + x2 + x3) / 3); cy = ~~((y1 + y2 + y3) / 3); // 获取中心点坐标的颜色值 index = (cy*imgData.width + cx)*4; var color_r = imgData.data[index]; var color_g = imgData.data[index+1]; var color_b = imgData.data[index+2]; // 绘制三角形 ctx.save(); ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x3, y3); ctx.closePath(); ctx.fillStyle = "rgba("+color_r+","+color_g+","+color_b+",1)"; ctx.fill(); ctx.restore(); }
One thing to note above is that the obtained center point coordinates must be rounded to get the correct color parameters. If you want not to round, but to round when getting the rgb index, you can get The color value is wrong. Because the pixel obtained in this way is not the center pixel we want.
After the color is obtained, it is a simple connection and then filling operation. The final effect is:
The above content introduces you to using canvas to achieve the effect of triangulating a picture (LOW POLY). I hope it will be helpful to you!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

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

Notepad++7.3.1
Easy-to-use and free code editor