本文摘自PHP中文网,作者不言,侵删。
canvas元素在html5中是用于在浏览器中画图的,所以canvas可以实现绘制很多不同的图,那么,今天我们就来看一看canvas如何来绘制一个椭圆形,话不多说,让我们来直接看正文吧。首先我们来看一下canvas自带的绘制椭圆的方法
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise)。
参数(从左到右):
(起点x,起点y,半径x,半径y,旋转的角度,起始角,结果角,顺时针还是逆时针)
我们来看canvas自带的绘制椭圆的方法代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <!DOCTYPE html>
< html >
< head >
< meta charset = "UTF-8" >
< title >椭圆</ title >
</ head >
< body >
< canvas id = "canvas" style = "border:1px solid #aaa;display:block;margin:50px auto;" >
当前浏览器不支持Canvas,请更换浏览器后再试
</ canvas >
< script >
window.onload = function(){
var canvas = document.getElementById("canvas");
var ctx=canvas.getContext('2d');
canvas.width = 800;
canvas.height = 800;
if(ctx.ellipse){
ctx.ellipse(300,300,200,100,0,0,Math.PI*2);
ctx.fillStyle="blue";
ctx.strokeStyle="#000";
ctx.fill();
ctx.stroke();
}else{
alert("no ellipse!");
}
}
</ script >
</ body >
</ html >
|
canvas画的椭圆效果如下:
说明:这种方法目前似乎只有谷歌支持,其他浏览器还未存在ellipse()。
既然上述方法无法支持其他浏览器,我们就来看看其他canvas绘制椭圆的方法。
一、利用canvas画圆的方法来绘制一个椭圆
这种方法用到了一个canvas函数scale,scale函数能实现canvas的缩放。缩放有水平和垂直两个方向,代码中把canvas水平方向放大了,而垂直方向不变,因此,原来arc画出的圆形就变成了一个椭圆。
canvas绘制椭圆的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <!DOCTYPE HTML>
< html >
< head >
< style >
body {
margin: 0px;
padding: 0px;
}
</ style >
</ head >
< body >
< canvas id = "myCanvas" width = "578" height = "200" ></ canvas >
< script >
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();
// apply styling
context.fillStyle = 'pink';
context.fill();
context.lineWidth = 5;
context.strokeStyle = 'black';
context.stroke();
</ script >
</ body >
</ html >
|
canvas椭圆效果如下:
阅读剩余部分
相关阅读 >>
h5 canvas api中drawimage(图像进行缩放或裁剪)的使用实例
如何用canvas实现在线签名的示例代码
使用canvas设计出一个简易的画板
html5 canvas实现粒子时钟的示例代码
html5 canvas标签是什么意思?canvas标签使用方法介绍
canvas波浪效果的实现代码
html5中如何绘制图形以及清空图像
canvas贝塞尔公式推导与物体跟随复杂曲线轨迹运动
使用canvas轻松实现黑客帝国炫酷代码雨!!
html5中canvas的使用--画线和面
更多相关阅读请进入《canvas》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » canvas如何来绘制一个椭圆形?canvas画椭圆的方法总结