您的位置:首页 > Web前端 > HTML5

html5画直线带箭头 画圆

2014-04-13 13:24 387 查看
参考资料

直接贴代码了,对旋转那里我也是瞎蒙的

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Text</title>
<script type="text/javascript">
window.onload = function(){

arrow2("myCanvas",0,0,0,0,300,100)
arrow2("myCanvas",0,0,200,200,150,150)
arrow2("myCanvas",0,0,20,200,150,150)
arrow2("myCanvas",0,0,100,0,50,100)
arrow2("myCanvas",0,0,0,100,300,100)
}
function arrow2(canId,ox,oy,x1,y1,x2,y2)
{
//参数说明 canvas的 id ,原点坐标  第一个端点的坐标,第二个端点的坐标
var sta = new Array(x1,y1);
var end = new Array(x2,y2);

var canvas = document.getElementById(canId);
if(canvas == null)return false;
var ctx = canvas.getContext('2d');
//画线
ctx.beginPath();
ctx.translate(ox,oy,0); //坐标源点
ctx.moveTo(sta[0],sta[1]);
ctx.lineTo(end[0],end[1]);
ctx.fill();
ctx.stroke();
ctx.save();
//画箭头
ctx.translate(end[0],end[1]);
//我的箭头本垂直向下,算出直线偏离Y的角,然后旋转 ,rotate是顺时针旋转的,所以加个负号
var ang=(end[0]-sta[0])/(end[1]-sta[1]);
ang=Math.atan(ang);
if(end[1]-sta[1] >= 0){
ctx.rotate(-ang);
}else{
ctx.rotate(Math.PI-ang);//加个180度,反过来
}
ctx.lineTo(-5,-10);
ctx.lineTo(0,-5);
ctx.lineTo(5,-10);
ctx.lineTo(0,0);
ctx.fill(); //箭头是个封闭图形
ctx.restore();
ctx.closePath();
}
</script>
<style type="text/css">
canvas{border:#ccc solid 1px;}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="300"></canvas>
</body>
</html>


画圆比较简单

ctx.beginPath();
ctx.fillStyle = "rgba(255,0,0,0.2)";
ctx.save();
ctx.translate(120,120);
ctx.arc(30,30,80,20*Math.PI/180,2*Math.PI,true); 
ctx.fill();
ctx.restore();
ctx.closePath();


arc的参数分别是(圆心x,圆心y,半径,起始角度,终止角度)  最后那个参数可选,规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针。

现在说一下save 和 restore的用法。 

首先说明的是,虽然每次调用函数,但是得到的canvas对象还是一个,如果知道opengl的pushMatrix和popMatrix的话,就明白他们是一个意思。就是把save之前的状态压到栈里,经过一番处理后,再把原来的栈弄出来(restore)

还有一点要注意:

在canvas中定义width、height跟在style中定义width和height是不同的,canvas标签的width和height是画布实际宽度和高度,绘制的图形都是在这个上面。而style的width和height是canvas在浏览器中被渲染的高度和宽度。如果canvas的width和height没指定或值不正确,就被设置成默认值(width:300px,height:150px)

前些天帮同学看了python画雪花的代码发现我的画法是基于坐标的,其实可以基于极坐标画,示例如下

import turtle
scale=3 #become longer
def koch(t, length):
if length < 3:
t.forward(length*scale)
return
x = length/3.0
koch(t, x)
t.left(60)
koch(t, x)
t.right(120)
koch(t, x)
t.left(60)
koch(t, x)
koch(turtle, 100):
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  html5 图形 2d