1. 第一步封装个函数 mainBgFullScreen 初始化 canvas
- width = $(':root').width();
- height = $(':root').height();
- zoom = getZoom();
- $canvas.attr('width', width);
- $canvas.attr('height', height);
- if ($canvas[0].getContext) {
- var ctx = $canvas[0].getContext('2d');
- ctx.fillStyle = '#ffffff';
- ctx.strokeStyle = 'rgba(255,255,255,0)';
- ctx.lineWidth = 1 * zoom;
- drawCanvas(ctx);
- }
2. 第二步在 drawCanvas 函数中根据一定的逻辑画点画线
1. 画点:
- function creatPoint() {
- var xsKew = (Math.random() - 0.5) * zoom; //x方向速度
- var ysKew = (Math.random() - 0.5) * zoom; //y方向速度
- var r = ~~ (Math.random() * 5 * zoom);
- var x = ~~ (Math.random() * (width - r)) + 2 * r;
- var y = ~~ (Math.random() * (height - r)) + 2 * r;
- var point = {
- x: x,
- y: y,
- xsKew: xsKew,
- ysKew: ysKew,
- r: r
- }
- return point;
- }
- //初始化先放200个点
- for (var i = 0; i < ~~ (200 * zoom); i++) {
- pointArry.push(creatPoint());
- }
- //drawCanvas函数中
- $.each(pointArry,
- function(index) {
- //绘制点
- ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
- ctx.fill();
- })
1. 画线
- //画线
- function drawLine(ctx, p1x, p1y, p2x, p2y) {
- var xDistance = Math.abs(p1x - p2x); //计算两点间的x距离
- var yDistance = Math.abs(p1y - p2y); //计算两点间的y距离
- var distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);
- if (distance <= 120) {
- ctx.fillStyle = '#ffffff'; //解决窗口缩放时圆点变黑
- ctx.strokeStyle = 'rgba(255,255,255,' + (1 - distance / 120) + ')';
- ctx.save();
- ctx.beginPath();
- ctx.moveTo(p1x, p1y);
- ctx.lineTo(p2x, p2y);
- ctx.stroke();
- ctx.restore();
- }
- }
- $.each(pointArry, function (index) {
- if (index != i) {
- drawLine(ctx, pointArry[i].x, pointArry[i].y, this.x, this.y);
- }
- });
3. 第三步就是让这些东西动起来,毫无疑问就是定时器了,这里用 requestAnimationFrame 递归,原因不用多说,性能好呗
- if (window.requestAnimationFrame) timer = window.requestAnimationFrame(drawCanvas.bind(this, ctx));
- else if (window.msRequestAnimationFrame) timer = window.msRequestAnimationFrame(drawCanvas.bind(this, ctx));
- else if (window.mozRequestAnimationFrame) timer = window.mozRequestAnimationFrame(drawCanvas.bind(this, ctx));
- else if (window.webkitRequestAnimationFrame) timer = window.webkitRequestAnimationFrame(drawCanvas.bind(this, ctx));
4. 第四步就看需求了,鼠标移动,鼠标附近的点与鼠标连线,其实经过上面的思路,这也很容易实现了,就是或取鼠标坐标,在循环画点时,与鼠标连线就可以了
- $canvas.on('mousemove', function (ev) {
- ev = ev || event;
- mouseX = ev.offsetX;
- mouseY = ev.offsetY;
- });
- //drawCanvas函数中
- if (mouseX > 0 && mouseY > 0) {
- drawLine(ctx, mouseX, mouseY, this.x, this.y);
- }
来源: http://www.jqhtml.com/10269.html