PDF版 ePub版

Ch12 三次贝塞尔曲线

bezierCurveTo()方法

context.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y);

绘制XP壁纸

<!DOCTYPE html>
<html lang="zh">
<meta charset="UTF-8">
<title>XP壁纸</title>
<style>
body { background: url("./images/bg3.jpg") repeat; }
#canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; }
</style>
<body>
<div id="canvas-warp">
<canvas id="canvas">
你的浏览器居然不支持Canvas？！赶快换一个吧！！
</canvas>
</div>

<script>
var canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 600;
var context = canvas.getContext("2d");
context.fillStyle = "#FFF";
context.fillRect(0,0,800,600);

drawPrairie(context);
drawSky(context);
for(var i=0; i <5; i++){
var x0 = 500 * Math.random() + 50;
var y0 = 200 * Math.random() + 50;
var c0 = 100 * Math.random() + 50;
drawCloud(context, x0, y0, c0);

}

};

function drawSky(cxt){
cxt.save();

cxt.beginPath();
cxt.moveTo(0, 420);
cxt.bezierCurveTo(250, 300, 350, 550, 800, 400);
cxt.lineTo(800,0);
cxt.lineTo(0,0);
cxt.closePath();

cxt.fillStyle = lineStyle;

cxt.fill();

cxt.restore();
}

function drawPrairie(cxt){
cxt.save();

cxt.beginPath();
cxt.moveTo(0, 420);
cxt.bezierCurveTo(250, 300, 350, 550, 800, 400);
cxt.lineTo(800,600);
cxt.lineTo(0,600);
cxt.closePath();

var lineStyle = cxt.createLinearGradient(0, 600, 600, 0);

cxt.fillStyle = lineStyle;
cxt.fill();

cxt.restore();
}

/*渲染单个云朵
context:  canvas.getContext("2d")对象
cx: 云朵X轴位置
cy: 云朵Y轴位置
cw: 云朵宽度
*/
function drawCloud(cxt, cx, cy, cw) {
//云朵移动范围即画布宽度
var maxWidth = 800;
//如果超过边界从头开始绘制
cx = cx % maxWidth;
//云朵高度为宽度的60%
var ch = cw * 0.6;
//开始绘制云朵

cxt.beginPath();
cxt.fillStyle = "white";
//创建渐变
var grd = cxt.createLinearGradient(0, 0, 0, cy);
cxt.fillStyle = grd;

//在不同位置创建5个圆拼接成云朵现状
cxt.arc(cx, cy, cw * 0.19, 0, 360, false);
cxt.arc(cx + cw * 0.08, cy - ch * 0.3, cw * 0.11, 0, 360, false);
cxt.arc(cx + cw * 0.3, cy - ch * 0.25, cw * 0.25, 0, 360, false);
cxt.arc(cx + cw * 0.6, cy, cw * 0.21, 0, 360, false);
cxt.arc(cx + cw * 0.3, cy - ch * 0.1, cw * 0.28, 0, 360, false);
cxt.closePath();

cxt.fill();
}
</script>
</body>
</html>

保存和恢复Canvas状态

context.save();

context.restore();