search
HomeWeb Front-endHTML TutorialCanvas implements high-order Bezier curve

This article mainly introduces the implementation of high-order Bezier curve (N-order Bezier curve generator) in canvas. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Write first

Since the native Canvas only supports up to third-order Bezier curves, what should I do if I want to add multiple control points? (Even most complex curves can be simulated with third-order Bezier) At the same time, it is difficult for us to clearly understand the position of the Bezier control points very intuitively and how much the control points should be set to form the curve we want. . In order to solve the above two pain points, there seems to be no N-level solution (js version) in the community, so this time the author is very serious about open source bezierMaker.js!

bezierMaker.js theoretically supports the generation of N-order Bezier curves, and also provides a testing ground for developers to add and drag control points to ultimately generate a set of drawing animations. It is very intuitive for developers to know the different generation curves corresponding to control points at different positions.

If you like this work, welcome to Star. After all, stars are hard-earned. .

Project address: here✨✨✨

Why is a testing site needed?

When drawing a complex high-order Bezier curve, you cannot know the precise location of the control points of the curve you need. By simulating in the test field, the coordinate values ​​of the control points can be obtained in real time. The obtained point coordinates can be converted into an object array and passed into the BezierMaker class to generate the target curve

Effect diagram


##Function

    ##[x] Any number of control points can be added to the test site
  1. [x] The test site supports displaying the formation animation of curve drawing
  2. [x] Control points can be freely dragged
  3. [x] Supports display of tangent lines in the formation process of Bezier curves
  4. [x] The drawing of Bezier curves of order 3 and below uses native API
Introduction

<script src="./bezierMaker.js"></script>

Draw

The above rendering is For the use of the test site, after you obtain the accurate coordinates of the control points through the test site, you can call bezierMaker.js to draw the curve directly.

/**
 * canvas canvas的dom对象
 * bezierCtrlNodesArr 控制点数组,包含x,y坐标
 * color 曲线颜色
 */
var canvas = document.getElementById(&#39;canvas&#39;)
//3阶之前采用原生方法实现
var arr0 = [{x:70,y:25},{x:24,y:51}]
var arr1 = [{x:233,y:225},{x:170,y:279},{x:240,y:51}]
var arr2 = [{x:23,y:225},{x:70,y:79},{x:40,y:51},{x:300, y:44}]
var arr3 = [{x:333,y:15},{x:70,y:79},{x:40,y:551},{x:170,y:279},{x:17,y:239}]
var arr4 = [{x:53,y:85},{x:170,y:279},{x:240,y:551},{x:70,y:79},{x:40,y:551},{x:170,y:279}]
var bezier0 = new BezierMaker(canvas, arr0, &#39;black&#39;)
var bezier1 = new BezierMaker(canvas, arr1, &#39;red&#39;)
var bezier2 = new BezierMaker(canvas, arr2, &#39;blue&#39;)
var bezier3 = new BezierMaker(canvas, arr3, &#39;yellow&#39;)
var bezier4 = new BezierMaker(canvas, arr4, &#39;green&#39;)
bezier0.drawBezier()
bezier1.drawBezier()
bezier2.drawBezier()
bezier3.drawBezier()
bezier4.drawBezier()

Drawing results

When there are less than 3 control points, the native API interface will be used. . When there are more than 2 control points, the function we implement will be used to draw the points.

Core principle

Drawing Bezier curve

The core point of drawing Bezier curve lies in the application of Bezier formula:



The P0-Pn in this formula represent various power operations from the starting point to each control point to the end point and the proportion t.

BezierMaker.prototype.bezier = function(t) { //贝塞尔公式调用
    var x = 0,
        y = 0,
        bezierCtrlNodesArr = this.bezierCtrlNodesArr,
        //控制点数组
        n = bezierCtrlNodesArr.length - 1,
        self = this
    bezierCtrlNodesArr.forEach(function(item, index) {
        if(!index) {
            x += item.x * Math.pow(( 1 - t ), n - index) * Math.pow(t, index) 
            y += item.y * Math.pow(( 1 - t ), n - index) * Math.pow(t, index) 
        } else {
        //factorial为阶乘函数
            x += self.factorial(n) / self.factorial(index) / self.factorial(n - index) * item.x * Math.pow(( 1 - t ), n - index) * Math.pow(t, index) 
            y += self.factorial(n) / self.factorial(index) / self.factorial(n - index) * item.y * Math.pow(( 1 - t ), n - index) * Math.pow(t, index) 
        }
    })
    return {
        x: x,
        y: y
    }
}

Traverse all points and calculate the current point on the Bezier curve based on the value of the current proportion t (0

The author will specifically explain the derivation of the Bezier formula in a later article. Now you only need to know that we use the Bezier formula to calculate the points at which the actual Bezier curve is divided into 1000 equal parts. , a class curve can be simulated by connecting each point with a straight line.

For the implementation of Bezier curve generation animation in the simulation field

This part of the relevant code can be referred to here

The overall idea is to use recursion to control each layer The points are treated as first-order Bessel functions to calculate the next layer of control points and corresponding connections. The author will leave the specific logic until the in-depth explanation of the Bezier curve formula principle and sort out the animation generation principle of the test site~

Related recommendations:

Use CSS to make Bezier Curve

Detailed explanation of the application of Bezier curve

Code demonstration for implementing canvas Bezier curve effect

The above is the detailed content of Canvas implements high-order Bezier curve. For more information, please follow other related articles on the PHP Chinese website!

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
What is the difference between an HTML tag and an HTML attribute?What is the difference between an HTML tag and an HTML attribute?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

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