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

Html5 Canvas 系列_绘图二

2017-01-18 17:08 351 查看
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title> Canvas 绘图</title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="cloud">
<meta name="Keywords" content="H5 Canvas 绘图">
<meta name="Description" content="使用Html5 Canvas 绘制图形">
</head>

<style type="text/css">
#canvas{
border: 1px solid #000;
display:block;
margin: 50px auto;
}
</style>

<body>
<canvas id="canvas">
您的浏览器不支持Canvas
</canvas>
</body>

<script type="text/javascript" src="http://www.w3school.com.cn/jquery/jquery.js"></script>
<script type="text/javascript">
//	得到 canvas 容器
var canvas = document.getElementById("canvas");

// 初始化Canvas
function init_canvas(canvas_id){
canvas.width = 800;
canvas.height = 800;
return canvas.getContext("2d");
}

//	五角星
// context:canvas 容器  outerR innerR:绘制半径,控制大小  x y:座标,控制位置  rot:倾斜度
function ph1(context, x, y, outerR, innerR, rot){
context.beginPath();
for(var i = 0; i < 5; i++){
var line_x = Math.cos((18 + i * 72 - rot) / 180 * Math.PI) * outerR + x;
var line_y = -Math.sin((18 + i * 72 - rot) / 180 * Math.PI) * outerR + y;
context.lineTo(line_x, line_y);

line_x = Math.cos((54 + i * 72 - rot) / 180 * Math.PI) * innerR + x;
line_y = -Math.sin((54 + i * 72 - rot) / 180 * Math.PI) * innerR + y;
context.lineTo(line_x, line_y);

}
context.closePath();
// 线条属性 lineJoin(线条相交时的展示) miter(尖角 默认值) bevel(斜阶) round(圆角)
context.lineJoin = "round";
// 线条相交时,内角与外角的距离最大值	只在 lineJoin = miter 时生效 默认为 10
//context.lineLimit = 10;
// 线条颜色
context.strokeStyle = "#fb5";
// 填充颜色
context.fillStyle = "#fb3";
// 线条粗细
context.lineWidth = 3;
// 进行填充
context.fill();
// 开始绘制
context.stroke();
}

//	绘制一片星空
function ph2(context, count){
//	设置填充颜色
context.fillStyle = "black";
//	绘制方形
context.fillRect(0, 0, canvas.width, canvas.height);
//  开始绘制
for(var i = 0 ; i < count ; i++){
// 随机产生半径 Math.random 的值在 0 到 1 之间
var r = Math.random() * 10 + 10;
// 随机 x y 座标
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
// 随机倾斜度
var rot = Math.random() * 360;
ph1(context, x, y, r, r / 2.0, rot);

}
}

$(function(){
var context = init_canvas("canvas");
ph2(context, 135);
// 其它方法: 位移 translate(x, y) 旋转 rotate(deg) 缩放scale(sx, sx)
});
</script>
</html>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  html5 canvas web