canvas 绘图详解
/* 图形变换 位移 translate(x, y) 会叠加 旋转 rotate (deg) 缩放 scale (sx, sy) */ /* * transform(a, b, c, d, e, f) * * a c e * b d f * 0 0 1 * /////////// * * a d 水平、垂直 缩放 * b c 水平、垂直 倾斜 * e f 水平、垂直 位移 * * * setTransform() * */
<!DOCTYPE html>
<html>
<head lang="en">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<canvas id="canvas" style="display: block;margin: 0 auto;border: 1px solid #aaa;">
你的浏览器不支持canvas
</canvas>
<script>
window.onload = function () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = 1024;
canvas.height = 768;
// context.fillStyle = "yellow";
// context.translate(300, 200);
// context.rotate (40);
// context.scale(3, 0.8);
// context.fillRect(0, 0, 200, 200);
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
for(var i=0; i < 200; i++){
var R = Math.random() * 10 + 10;
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var rot = Math.random() * 360;
drawStar(context, R, x, y, rot);
}
}
// r 内圆半径 = R 外圆半径 (x, y) Star 中心坐标 rot 角度
function drawStar(context,R, x, y, rot){
context.save();
context.translate(x, y);
context.rotate(rot / 180 * Math.PI);
context.scale(R, R);
starPath(context);
// 绘制 大小为R (x, y) Star 中心坐标 rot 角度 的五角星
/* 图形变换
位移 translate(x, y) 会叠加
旋转 rotate (deg)
缩放 scale (sx, sy)
*/
/*
* transform(a, b, c, d, e, f)
*
* a c e
* b d f
* 0 0 1
* ///////////
*
* a d 水平、垂直 缩放
* b c 水平、垂直 倾斜
* e f 水平、垂直 位移
*
*
* setTransform()
* */
context.fillStyle = "#fd5";
// context.strokeStyle = "#ddd";
// context.lineWidth = 1;
// context.lineJoin = "round";
context.fill();
// context.stroke();
context.restore();
/**
*
*/
}
function starPath(context){
context.beginPath();
for(var i =0; i < 5; i++){
context.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI),
-Math.sin((18 + i * 72) / 180 * Math.PI));
context.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * 0.5,
-Math.sin((54 + i * 72 ) / 180 * Math.PI) * 0.5);
}
context.closePath();
}
</script>
</body>
</html>
本文介绍使用HTML5 Canvas进行复杂图形绘制的方法,包括变换操作如平移、旋转和缩放等,并通过实例展示如何绘制随机分布的五角星图案。
290

被折叠的 条评论
为什么被折叠?



