search
HomeWeb Front-endHTML TutorialDetailed explanation of how canvas uses Bezier curves to smoothly fit polyline segments

This article mainly introduces the relevant information on the method of smoothly fitting polyline segments using Bezier curve based on canvas. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Write at the front

This time I will share how to "smooth" the edges and corners of the drawn polyline segments in canvas, that is, through the Bezier curve Each plotted point replaces the original line chart.

Why we need to smoothly fit polyline segments

Let’s first look at the rendering effect of the line chart under Echarts:

At first I didn’t notice that this polyline segment was actually passed through by a curve. I just thought it was a simple point drawing, so the “simple (ugly) easy (ugly)” version I implemented at first was like this:

Don’t pay attention to the style. The point is that after implementation, I discovered that the implementation of Echarts seems to be very smooth, which also triggered subsequent discussions. How to draw smooth curves regularly?

Rendering

Let’s take a look at the final imitation implementation:

Because I don’t know how Echarts is implemented internally (escape

It looks very round, very close to our original idea. Let’s see if the curve passes through the drawing point:

Okay! The result is obvious. Now let’s take a look at our implementation process

    Drawing a line chart
  1. Bezier curve smooth fitting
  2. Simulated data

##
var data = [Math.random() * 300];
        for (var i = 1; i < 50; i++) { //按照echarts
            data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]));
        }
        option = {
            canvas:{
                id: &#39;canvas&#39;
            },
            series: {
                name: &#39;模拟数据&#39;,
                itemStyle: {
                    color: &#39;rgb(255, 70, 131)&#39;
                },
                areaStyle: {
                    color: &#39;rgb(255, 158, 68)&#39;
                },
                data: data
            }
        };

Drawing a line chart

First initialize a constructor to place the required data:

function LinearGradient(option) {
    this.canvas = document.getElementById(option.canvas.id)
    this.ctx = this.canvas.getContext(&#39;2d&#39;)
    this.width = this.canvas.width
    this.height = this.canvas.height
    this.tooltip = option.tooltip
    this.title = option.text
    this.series = option.series //存放模拟数据
}

Draw a line chart:

LinearGradient.prototype.draw1 = function() { //折线参考线
    ... 
    //要考虑到canvas中的原点是左上角,
    //所以下面要做一些换算,
    //diff为x,y轴被数据最大值和最小值的取值范围所平分的等份。
    this.series.data.forEach(function(item, index) {
        var x = diffX * index,
            y = Math.floor(self.height - diffY * (item - dataMin))
        self.ctx.lineTo(x, y) //绘制各个数据点
    })
    ...
}


Bezier curve smooth fitting

The key point of Bezier curve is the selection of control points. This website can dynamically display different curves drawn with different control points. As for the calculation of control points... the author still chose Baidu because he is not good at mathematics:). Students who are interested in the specific algorithm can learn more about it. Now let’s talk about the conclusion of calculating control points.

The above formula involves four coordinate points, the current point, the previous point and the next two points, and when the coordinate values ​​​​are shown in the figure below, it is drawn The curve is as follows:

#However, there is a problem that this formula cannot be used for the starting point and the last point, but that article also gives a method for handling boundary values. :

So when changing the polyline to a smooth curve, calculate the boundary values ​​and other control points and then substitute them into the Bessel function:

//核心实现
this.series.data.forEach(function(item, index) { //找到前一个点到下一个点中间的控制点
    var scale = 0.1 //分别对于ab控制点的一个正数,可以分别自行调整
    var last1X = diffX * (index - 1),
        last1Y = Math.floor(self.height - diffY * (self.series.data[index - 1] - dataMin)),
        //前一个点坐标
        last2X = diffX * (index - 2),
        last2Y = Math.floor(self.height - diffY * (self.series.data[index - 2] - dataMin)),
        //前两个点坐标
        nowX = diffX * (index),
        nowY = Math.floor(self.height - diffY * (self.series.data[index] - dataMin)),
        //当期点坐标
        nextX = diffX * (index + 1),
        nextY = Math.floor(self.height - diffY * (self.series.data[index + 1] - dataMin)),
        //下一个点坐标
        cAx = last1X + (nowX - last2X) * scale,
        cAy = last1Y + (nowY - last2Y) * scale,
        cBx = nowX - (nextX - last1X) * scale,
        cBy = nowY - (nextY - last1Y) * scale 
    if(index === 0) {
        self.ctx.lineTo(nowX, nowY)
        return
    } else if(index ===1) {
        cAx = last1X + (nowX - 0) * scale
        cAy = last1Y + (nowY - self.height) * scale 
    } else if(index === self.series.data.length - 1) {
        cBx = nowX - (nowX - last1X) * scale
        cBy = nowY - (nowY - last1Y) * scale
    } 
        self.ctx.bezierCurveTo(cAx, cAy, cBx, cBy, nowX, nowY);
        //绘制出上一个点到当前点的贝塞尔曲线
    })

Since the point I traverse each time is the current point, but the formula given in the article is a control point algorithm that calculates the next point, so in the code implementation I moved all the point calculations forward one position. When index = 0, which is the initial point, no curve is required to be drawn, because we are drawing a curve from the previous point to the current point, and there is no curve to 0 that needs to be drawn. Starting from index = 1, we can start drawing normally. The curve from 0 to 1, because there is no second point in front of it when index = 1, it is a boundary value point, which requires special calculation, and finally one point. The rest can be calculated according to the normal formula and the xy coordinates of AB are substituted into the Bessel function.

Related recommendations:


Canvas implements high-order Bezier curve

Use CSS to make Bezier curve

Detailed explanation of the application of Bezier curve

The above is the detailed content of Detailed explanation of how canvas uses Bezier curves to smoothly fit polyline segments. 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
The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

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
4 weeks 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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft