简单的canvas绘图demo
最近在看canvas基础知识,刚学完绘制路径、矩形,设置线条、颜色、样式和阴影等,就想码下demo巩固下基础知识。于是网上搜了,找到了绘制XP壁纸的例子,里面用到了前面说到的各个知识点。好了,进入主题了。
html代码:
<canvas id="canvas" style="border: 1px solid #aaaaaa; display: block; margin: 50px auto;">浏览器居然不支持Canvas?赶快换一个吧!!</canvas>
js代码:
window.onload = function() {
var canvas = document.getElementById("canvas");
canvas.width = 800; //设置canvas的宽度
canvas.height = 600; //设置canvas的高度
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();
var lineStyle = cxt.createRadialGradient(400, 0, 50, 400, 0, 200);
lineStyle.addColorStop(0, "#42A9AA");
lineStyle.addColorStop(1, "#2491AA");
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);
lineStyle.addColorStop(0, "#00AA58");
lineStyle.addColorStop(0.3, "#63AA7B");
lineStyle.addColorStop(1, "#04AA00");
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);
grd.addColorStop(0, 'rgba(255,255,255,0.8)');
grd.addColorStop(1, 'rgba(255,255,255,0.5)');
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();
}
其中蓝天和草坪交接处的三次贝塞尔曲线可以根据以下链接生成自己喜欢的弧度。
http://blogs.sitepointstatic.com/examples/tech/canvas-curves/bezier-curve.html
还有二次贝塞尔曲线可以根据以下链接生成自己喜欢的弧度。
手机阅读请扫描下方二维码:
12345678
12345678
12345678
12345678
12345678
12345678
12345678
555
555
555
555
1
12345678
12345678
12345678 "and"w"="w
12345678 "and"f"="y
12345678
12345678
12345678
12345678 '//and(select'1'from//pg_sleep(3))>'0
12345678 'and(select+1)>0waitfor/**/delay'0:0:0
12345678
1
1
1
1
1
1
1
1
1
1
1
555
1
1
1
12345678
12345678
12345678
12345678
12345678
12345678
12345678
iojjhjtqbsklvpjdqyea
12345678
12345678
12345678
1
1
555
1
1
1
1
1
1
1
1
1
555
1
1
1
1
1
1
555
1
1
555
1
555
1
1
1
1
1
1
1
1
1
1
1
1