Home Web Front-end H5 Tutorial Canvas画椭圆的方法

Canvas画椭圆的方法

May 17, 2016 am 09:07 AM

  虽然标题是画椭圆,但是我们先来说说Canvas中的圆

  相信大家对于Canvas画圆都不陌生

oGC.arc(400, 300, 100, 0, 2*Math.PI, false);
复制代码
Copy after login


  如上所示,直接调用API就可以了,但是计算机内部却是使用光栅学,利用bresenham算法画圆的,这个我们放到最后来说,先说说利用圆的参数方程画圆

circle(oGC, 400, 300, 100);
function circle(context, x, y, a) { // x,y是坐标;a是半径
    var r = 1/a; // ①注意:此处r可以写死,不过不同情况下写死的值不同
    context.beginPath();
    context.moveTo(x + a, y);
    for(var i = 0; i < 2 * Math.PI; i += r) {
        context.lineTo(x + a * Math.cos(i), y + a * Math.sin(i));
    }
    context.closePath();
    context.fill();
}
复制代码
Copy after login


  原理是什么,相信三角函数不错的童鞋理解起来很容易的,如果不知道的话,注意注释①,我变化一下r的值,相信就立竿见影了~

1073.png


1074.png


1075.png


1076.png


  r和2*Math.PI配合就是圆的精细程度,在半径为100的时候,r取1/10就可以了,通用的话可以写死,写成r = 1 / a;这样无论半径取大或者小,圆都会很精细,但是性能会有很大影响

  现在来看看文章的主角,针对圆来看椭圆的

function EllipseOne(context, x, y, a, b) {
    var step = (a > b) ? 1 / a : 1 / b;
    context.beginPath();
    context.moveTo(x + a, y);
    for(var i = 0; i < 2 * Math.PI; i += step) {
        context.lineTo(x + a * Math.cos(i), y + b * Math.sin(i));
    }
    context.closePath();
    context.fill();
}
复制代码
Copy after login


  和圆基本一样,不过圆只有一个半径,而椭圆分为长轴和短轴了。

  看下效果~

1077.png


  好了,画椭圆成功,文章结束~

  怎么可能!

  就这样结束也太没品了,刚刚是方法一,下面来看其他的

  方法二,均匀压缩法

  这是我最喜欢的方法,易理解,相比较方法一,性能也快了很多,先贴代码~

  1. function EllipseTwo(context, x, y, a, b) {
        context.save();
        var r = (a > b) ? a : b;
        var ratioX = a / r;
        var ratioY = b / r;
        context.scale(ratioX, ratioY);
        context.beginPath();
        context.arc(x / ratioX, y / ratioY, r, 0, 2 * Math.PI, false);
        context.closePath();
        context.restore();
        context.fill();
    }
    Copy after login
复制代码


  原理是利用了scale来对一个标准的圆进行压缩,ratioX是横轴缩放比率,ratioY是纵轴缩放比率,就因为这两个值不同,使得将标准圆缩放成了一个椭圆

  记得save()和restore()还原context环境,so easy理解的方法

  下面两种方法很高大上,都是利用三次贝塞尔曲线法

  方法三,四,贝塞尔法

function EllipseThree(context, x, y, a, b) {
    var ox = 0.5 * a,
        oy = 0.6 * b;
    context.save();
    context.translate(x, y);
    context.beginPath();
    context.moveTo(0, b);
    context.bezierCurveTo(ox, b, a, oy, a, 0);
    context.bezierCurveTo(a, -oy, ox, -b, 0, -b);
    context.bezierCurveTo(-ox, -b, -a, -oy, -a, 0);
    context.bezierCurveTo(-a, oy, -ox, b, 0, b);
    context.closePath();
    context.fill();
    context.restore();
}
function EllipseFour(context, x, y, a, b) {
    var k = 0.5522848,
    ox = k * a,
    oy = k * b;
    context.translate(x, y);
    context.beginPath();
    context.moveTo(-a, 0);
    context.bezierCurveTo(-a, oy, -ox, -b, 0, -b);
    context.bezierCurveTo(ox, -b, a, -oy, a, 0);
    context.bezierCurveTo(a, oy, ox, b, 0, b);
    context.bezierCurveTo(-ox, b, -a, oy, -a, 0);
    context.closePath();
    context.fill();
}
复制代码
Copy after login
  贝塞尔法的核心在于两个控制点的选取,但是它有致命的问题,当lineWidth较宽的时候,椭圆较扁,长轴较尖锐,会出现不平滑的情况

  如果不知道什么事贝塞尔的话就自行百度……这个不解释了……

  后面还有最后一种光栅法画椭圆,光栅法画圆很简单,画椭圆挺麻烦的,下面是最简单的一种椭圆画法,等于是lineWidth为1px的情况下
function EllipseFive(context, x, y, a, b) {
    var data = context.getImageData(0, 0, 800, 600);
    var imageData = data.data;
    var tx = 0;
    var ty = b;
    var d = b*b + a*a*(-b + 0.25);
    var mx = a * a / Math.sqrt(a * a + b * b);
    while(tx <= mx) {
        if(d < 0) {
            d += b * b * (2 * tx + 3);
        } else {
            ty--;
            d += b * b * (2 * tx + 3) + 2 * a * a * (1 - ty);
            
        }
        tx++;
        setPix(x + tx, y + ty);
        setPix(x + tx, y - ty);
        setPix(x - tx, y + ty);
        setPix(x - tx, y - ty);
    }
    d = b * b * (tx + 0.5) * (tx + 0.5) + a * a * (ty - 1) * (ty - 1) - a * a * b * b;
    while (ty > 0) {
        if (d < 0) {
            tx++;
            d += b*b*(2 * tx + 2) + a*a*(-2 * ty + 3);
        }
        else {
            d += a*a*(-2 * ty + 3);
        }
        ty--;
        setPix(x + tx, y + ty);
        setPix(x - tx, y + ty);
        setPix(x + tx, y - ty);
        setPix(x - tx, y - ty);
    }
    context.putImageData(data, 0, 0);
    function setPix(x, y){
        console.log(x, y);
        var index = getStartIndex(x, y);
        for(var i = 0; i< 4; i++) {
            if(i == 3) {
                imageData[index + i] = 255;
            }
            else{
                imageData[index + i] = 128;
            }
        }
    }
    function getStartIndex(x, y) {
        return y * 800 * 4 + x * 4;
    }
}
复制代码
Copy after login


  给个结果图~

1078.png


  光栅法的原理在这里就不说啦,那个说的话篇幅很大,在这里也不推荐用光栅法去画椭圆,针对不同线宽很麻烦

  ok这篇文章就到这啦,Thanks~

以上就是Canvas画椭圆的方法的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Which schools use canvas? Which schools use canvas? Aug 18, 2023 pm 05:59 PM

Schools using canvas include Stanford University, MIT, Columbia University, University of California, Berkeley, etc. Detailed introduction: 1. Stanford University uses Canvas as its main online learning platform. Teachers and students at Stanford University use Canvas to manage and communicate course content, and learn through functions such as online discussions, assignment submissions, and exams; 2. Ma Provincial Polytechnic Institute and MIT also use Canvas as their online learning management system and conduct course management through the Canvas platform; 3. Columbia University, etc.

What are the canvas arrow plug-ins? What are the canvas arrow plug-ins? Aug 21, 2023 pm 02:14 PM

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.

What are the details of the canvas clock? What are the details of the canvas clock? Aug 21, 2023 pm 05:07 PM

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.

What versions of html2canvas are there? What versions of html2canvas are there? Aug 22, 2023 pm 05:58 PM

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.

uniapp implements how to use canvas to draw charts and animation effects uniapp implements how to use canvas to draw charts and animation effects Oct 18, 2023 am 10:42 AM

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

For which styles is html2canvas invalid? For which styles is html2canvas invalid? Nov 24, 2023 pm 03:25 PM

Invalid styles include CSS3 animations and transitions, CSS filter effects, CSS3 complex graphics and paths, some CSS3 features, pseudo elements and some CSS features, Z-index, background images and gradients, etc. Detailed introduction: 1. CSS3 animation and transition: html2canvas may not fully capture CSS3 animation and transition effects. Although attempts will be made to capture the final style, these animations and transitions may be lost during the conversion process; 2. CSS filter effects: filters such as blur and shadow may not be retained during the conversion process, etc.

The development trend and future prospects of Canvas in China's education sector The development trend and future prospects of Canvas in China's education sector Jan 17, 2024 am 10:22 AM

With the rapid development of science and technology and the widespread application of information technology in the field of education, Canvas, as a world-leading online learning management system, is gradually emerging in the Chinese education industry. The emergence of Canvas provides new possibilities for the reform of education and teaching methods in China. This article will explore the development trends and prospects of Canvas in China’s education sector. First of all, one of the development trends of Canvas in China’s education sector is in-depth integration. With the rapid development of cloud computing, big data and artificial intelligence, Canvas will increasingly

What properties does tkinter canvas have? What properties does tkinter canvas have? Aug 21, 2023 pm 05:46 PM

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

See all articles