html5 canvas画云

使用函数画出天空的云层图像:

云层y





主要使用到的是数学的圆与弧度之间转换关系:

代码如下


//div对象
var parentContainer = document.getElementById("container");


(function(window) {
var utils = window.utils || {};
window.utils = utils || window.utils;
/**
* 获取1-seek的随机值
*/
utils.getRandom = function(seek) {
return parseInt(Math.random() * seek + 1);
}
utils.PI = Math.PI;
utils.ROUND = Math.PI * 2;

//根据弧度计算出水平位置长度
utils.getTranslateX = function(r, radious) {
return parseInt(Math.abs(2 * r * Math.sin(90 * radious / 180)));
}
utils.drawCloud = function(container) {
container.moveTo(0, 80);
var i = 0;
var maxWidth = parentContainer.clientWidth;
var x = 0, y = 60, x1 = 0, y1 = 60;
//一弧度=180/pi
container.beginPath();
while (x <= maxWidth) {
var r = utils.getRandom(15);
var radious = utils.getRandom(360) / Math.PI;
var nextX = utils.getTranslateX(r, radious);
container.arc(x + r, y, r, 0, radious, false);
x += nextX;
}


container.closePath();
container.fillStyle = "white";
container.fillRect(0, 60, maxWidth, 60);
container.fill();
}
})(window);


(function(window) {
var canvas = document.createElement("canvas");
canvas.style.position = "absolute";
var ctx = canvas.getContext("2d");
parentContainer.appendChild(canvas);
utils.drawCloud(ctx);


// var c = document.createElement("canvas");
// c.style.position = "absolute";
// cx = c.getContext("2d");
// parentContainer.appendChild(c);
//
// cx.fillText("00000", 70, 50, 50, 50);
})(window)













posted @ 2014-04-08 14:38  小小架构师  阅读(347)  评论(0编辑  收藏  举报