


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;ivar 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.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.


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

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.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.
