


html5 Canvas drawing tutorial (11)—Use lineTo/arc/bezierCurveTo to draw an oval_html5 tutorial skills
In canvas, you can easily use the arc method to draw a circle. Originally, a circle can also be regarded as an ellipse with equal width and height, but there is no way to draw an ellipse in canvas. We have to use other methods to simulate it.
We must first clarify what parameters are needed to draw an ellipse. Basic geometric knowledge tells us that an ellipse requires center coordinates, width, height - or rotation angle, but this can be omitted for the time being, rotation is easier.
1. Use lineTo to draw ellipses
You read that right, lineTo, a method purely used to draw straight lines, can actually be used to draw ellipses! ? But he does exist, but the writing method is really incredible:
function DrawEllipse(Canvas,O,OA,OB){
//Draw an ellipse, example: var B=new Array(150,150); DrawEllipse(hb,B,50,30);
with ( Canvas){
var x=O[0] OA;
var y=O[1];
moveTo(x,y);
for (var i=0;i<=360 ;i ){
var ii=i*Math.PI/180;
var x=O[0] OA*Math.cos(ii);
var y=O[1]-OB* Math.sin(ii);
lineTo(x,y);
}
}
}
The principle of this method is that a circle has 360 degrees, Then use lineTo to loop 360 times, draw line segments for each degree, and finally connect them into an ellipse. The trigonometric functions sine and cosine are required for calculation.
Note that the second parameter of this method is an array, which is the center coordinate of the ellipse.
The idea is very strange, and the ellipse drawn is relatively smooth. But it’s not worth using for everyone – this method will cycle 360 times every time it draws an ellipse, and only draws slightly more ellipses, which is a test for the performance of the browser.
We just need to understand his ideas
2. Use arc to draw a circle, and then scale it into an ellipse
The original text of this method is here, and the core function is as follows:
var canvas = document.getElementById('myCanvas ');
var context = canvas.getContext('2d');
var centerX = 0;
var centerY = 0;
var radius = 50;
// save state
context.save();
// translate context
context.translate(canvas.width / 2, canvas.height / 2);
// scale context horizontally
context.scale( 2, 1);
// draw circle which will be stretched into an oval
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false );
// restore to original state
context.restore()
This method uses a canvas function that I haven’t talked about before, namely scale, which can implement canvas of zoom. There are two directions of scaling: horizontal and vertical. In the code, the canvas is enlarged in the horizontal direction, but the vertical direction remains unchanged. So, the circle drawn by arc becomes an ellipse.
This method looks very good at first glance, with less code and the principle is easy to understand. But after analysis, you can find his obvious shortcomings, which is - imprecision! For example, I need an ellipse with a width of 171 and a height of 56. If we set the radius of arc to 28, then we will be depressed by the painful and incomprehensible number 171/28/2.
But a compromise is to always set the radius of arc to 100, and then enlarge it if it is not enough, and shrink it if it exceeds it. However, it's still not precise.
3, use Bezier curve bezierCurveTo
Since I felt that the scaling method above was inaccurate, I wanted to find an accurate method of drawing an ellipse, and finally found it on stackoverflow:
function drawEllipse(ctx, x, y, w, h) {
var kappa = 0.5522848;
ox = (w / 2) * kappa, // control point offset horizontal
oy = (h / 2) * kappa, // control point offset vertical
xe = x w, // x-end
ye = y h, // y-end
xm = x w / 2, // x-middle
ym = y h / 2; // y-middle
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym oy, xm ox, ye, xm, ye);
ctx.bezierCurveTo( xm - ox, ye, x, ym oy, x, ym);
ctx.closePath();
ctx.stroke();
}
This method can be considered perfect. He divided an ellipse into four Bezier curves and connected them to form an ellipse. Finally, the width and height are more accurate and the overhead is less.
But this method still has shortcomings. Look at the kappa parameter, it has a very peculiar value. I believe many people don’t understand why it has to be this value until a geometry expert tells you why it has to be this value - I still don’t know. And I have a strong urge to change it and see what the consequences will be.
Of course, my impulse similar to that of an obsessive-compulsive disorder patient cannot be said to be a shortcoming of this method. Its real shortcoming is-why use 4 Bezier curves? I personally feel that an ellipse is obviously composed of two Bezier curves instead of four. This idea eventually led me to the perfect way to draw an ellipse.
4, use two Bezier curves to draw an ellipse
In order to understand whether the previous method can be simplified, I specially registered a stackoverflow account to ask questions. Since there are pictures in the question, I didn’t have enough points to transfer, so I had to use my barely adequate English to answer questions from foreigners to earn points. But luck finally came and my points problem was solved by answering a question.
The question I asked about the relationship between Bezier curves and ellipses is here.
To be honest, I didn’t understand most of the foreigner’s answers below, but fortunately he provided a code sample page, which made me understand. Principle, I would like to express my gratitude to him again. According to his answer, the method I found to draw an ellipse is as follows:
//Ellipse
CanvasRenderingContext2D.prototype.oval = function (x, y, width, height) {
var k = (width/0.75)/2,
w = width/ 2,
h = height/2;
this.beginPath();
this.moveTo(x, y-h);
this.bezierCurveTo(x k, y-h, x k, y h, x, y h );
this.bezierCurveTo(x-k, y h, x-k, y-h, x, y-h);
this.closePath();
return this;
}
This method is precise, requires less code, and doesn't have any weird quirks. Just remember this, the ratio of the width of the ellipse to the coordinates of the control points of the Bezier curve that draws the ellipse is as follows:
Bezier control point x=(ellipse width/0.75)/2 This is already in the code reflected in.
You can try the above 4 methods to draw an ellipse.
If you find a simpler method, please share it with us for discussion.

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Intel's next-generation GPU architecture is expected to launch in September as part of Intel Lunar Lake. Like the Arc Alchemist iGPU from Meteor Lake, the iGPU has up to 8 Xe cores, but the new architecture is expected to achieve 50% higher performan

The canvas arrow plug-ins include: 1. Fabric.js, which has a simple and easy-to-use API and can create custom arrow effects; 2. Konva.js, which provides the function of drawing arrows and can create various arrow styles; 3. Pixi.js , which provides rich graphics processing functions and can achieve various arrow effects; 4. Two.js, which can easily create and control arrow styles and animations; 5. Arrow.js, which can create various arrow effects; 6. Rough .js, you can create hand-drawn arrows, etc.

The details of the canvas clock include clock appearance, tick marks, digital clock, hour, minute and second hands, center point, animation effects, other styles, etc. Detailed introduction: 1. Clock appearance, you can use Canvas to draw a circular dial as the appearance of the clock, and you can set the size, color, border and other styles of the dial; 2. Scale lines, draw scale lines on the dial to represent hours or minutes. Position; 3. Digital clock, you can draw a digital clock on the dial to indicate the current hour and minute; 4. Hour hand, minute hand, second hand, etc.

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

The versions of html2canvas include html2canvas v0.x, html2canvas v1.x, etc. Detailed introduction: 1. html2canvas v0.x, which is an early version of html2canvas. The latest stable version is v0.5.0-alpha1. It is a mature version that has been widely used and verified in many projects; 2. html2canvas v1.x, this is a new version of html2canvas.

How to use canvas to draw charts and animation effects in uniapp requires specific code examples 1. Introduction With the popularity of mobile devices, more and more applications need to display various charts and animation effects on the mobile terminal. As a cross-platform development framework based on Vue.js, uniapp provides the ability to use canvas to draw charts and animation effects. This article will introduce how uniapp uses canvas to achieve chart and animation effects, and give specific code examples. 2. canvas

The tkinter canvas attributes include bg, bd, relief, width, height, cursor, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertwidth, selectbackground, selectforeground, xscrollcommand attributes, etc. Detailed introduction

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use
