[收藏]一些js特效

  1. 鼠标跟随特效
    鼠标后有随机颜色的❄跟随
(function fairyDustCursor(){var possibleColors=["#D61C59","#E7D84B","#1B8798"];var width=window.innerWidth;var height=window.innerHeight;var cursor={x:width/2,y:width/2};var particles=[];function init(){bindEvents();loop()}function bindEvents(){document.addEventListener("mousemove",onMouseMove);window.addEventListener("resize",onWindowResize)}function onWindowResize(e){width=window.innerWidth;height=window.innerHeight}function onMouseMove(e){cursor.x=e.clientX;cursor.y=e.clientY;addParticle(cursor.x,cursor.y,possibleColors[Math.floor(Math.random()*possibleColors.length)])}function addParticle(x,y,color){var particle=new Particle();particle.init(x,y,color);particles.push(particle)}function updateParticles(){for(var i=0;i<particles.length;i++){particles[i].update()}for(var i=particles.length-1;i>=0;i--){if(particles[i].lifeSpan<0){particles[i].die();particles.splice(i,1)}}}function loop(){requestAnimationFrame(loop);updateParticles()}function Particle(){this.character="❉";this.lifeSpan=60;this.initialStyles={"position":"fixed","display":"inline-block","top":"0px","left":"0px","pointerEvents":"none","touch-action":"none","z-index":"10000000","fontSize":"25px","will-change":"transform"};this.init=function(x,y,color){this.velocity={x:(Math.random()<0.5?-1:1)*(Math.random()/2),y:1};this.position={x:x+10,y:y+10};this.initialStyles.color=color;this.element=document.createElement("span");this.element.innerHTML=this.character;applyProperties(this.element,this.initialStyles);this.update();document.querySelector(".js-cursor-container").appendChild(this.element)};this.update=function(){this.position.x+=this.velocity.x;this.position.y+=this.velocity.y;this.lifeSpan--;this.element.style.transform="translate3d("+this.position.x+"px,"+this.position.y+"px, 0) scale("+(this.lifeSpan/120)+")"};this.die=function(){this.element.parentNode.removeChild(this.element)}}function applyProperties(target,properties){for(var key in properties){target.style[key]=properties[key]}}if(!("ontouchstart" in window||navigator.msMaxTouchPoints)){init()}})();
  1. 鼠标点击特效
    点击鼠标左键,出现小图片[需要引入图片background-image:url(./img/jump-pig.gif)]
(function(window,document,undefined){var hearts=[];window.requestAnimationFrame=(function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){setTimeout(callback,1000/60)}})();init();function init(){css(".heart{z-index:100000000;width:50px;height:50px;position:fixed;background-image:url(./img/jump-pig.gif);background-size:50px 50px;");attachEvent();gameloop()}function gameloop(){for(var i=0;i<hearts.length;i++){if(hearts[i].alpha<=0){document.body.removeChild(hearts[i].el);hearts.splice(i,1);continue}hearts[i].y--;hearts[i].scale+=0.004;hearts[i].alpha-=0.013;hearts[i].el.style.cssText="left:"+hearts[i].x+"px;top:"+hearts[i].y+"px;opacity:"+hearts[i].alpha+";transform:scale("+hearts[i].scale+","+hearts[i].scale+");"}requestAnimationFrame(gameloop)}function attachEvent(){var old=typeof window.onclick==="function"&&window.onclick;window.onclick=function(event){old&&old();createHeart(event)}}function createHeart(event){var d=document.createElement("div");d.className="heart";hearts.push({el:d,x:event.clientX-5,y:event.clientY-35,scale:1,alpha:1});document.body.appendChild(d)}function css(css){var style=document.createElement("style");style.type="text/css";try{style.appendChild(document.createTextNode(css))}catch(ex){style.styleSheet.cssText=css}document.getElementsByTagName("head")[0].appendChild(style)}})(window,document);
  1. 飞速烟花特效
    随机烟花;点击鼠标左键,向箭头处发射烟花;长按鼠标左键,发射连续烟花;
    [需要 引入jquery文件并设置一个canvas容器 <canvas id="canvas"></canvas>]

	//https://www.cnblogs.com/fpcbk/
	var timer = setInterval(function(){
		$(".box > div").animate({
			'marginLeft': 1000,
		},{queue:true, duration:5000,complete:function a(){
			 $(".box > div").css('transform','rotateY(180deg)');
		}}).animate({
			'marginLeft': 50,
		},5000,function(){
			 $(".box > div").css('transform','rotateY(0deg)');
		});
	},1000);
	// when animating on canvas, it is best to use requestAnimationFrame instead of setTimeout or setInterval
	// not supported in all browsers though and sometimes needs a prefix, so we need a shim
	window.requestAnimFrame = ( function() {
		return window.requestAnimationFrame ||
			window.webkitRequestAnimationFrame ||
			window.mozRequestAnimationFrame ||
			function( callback ) {
				window.setTimeout( callback, 1000 / 60 );
			};
	})();

	// now we will setup our basic variables for the demo
	var canvas = document.getElementById( 'canvas' ),
		ctx = canvas.getContext( '2d' ),
		// full screen dimensions
		cw = window.innerWidth,
		ch = window.innerHeight,
		// firework collection
		fireworks = [],
		// particle collection
		particles = [],
		// starting hue
		hue = 120,
		// when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks
		limiterTotal = 5,
		limiterTick = 0,
		// this will time the auto launches of fireworks, one launch per 80 loop ticks
		timerTotal = 80,
		timerTick = 0,
		mousedown = false,
		// mouse x coordinate,
		mx,
		// mouse y coordinate
		my;
			
	// set canvas dimensions
	canvas.width = cw;
	canvas.height = ch;

	// now we are going to setup our function placeholders for the entire demo

	// get a random number within a range
	function random( min, max ) {
		return Math.random() * ( max - min ) + min;
	}

	// calculate the distance between two points
	function calculateDistance( p1x, p1y, p2x, p2y ) {
		var xDistance = p1x - p2x,yDistance = p1y - p2y;
		return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
	}

	// create firework
	function Firework( sx, sy, tx, ty ) {
		// actual coordinates
		this.x = sx;
		this.y = sy;
		// starting coordinates
		this.sx = sx;
		this.sy = sy;
		// target coordinates
		this.tx = tx;
		this.ty = ty;
		// distance from starting point to target
		this.distanceToTarget = calculateDistance( sx, sy, tx, ty );
		this.distanceTraveled = 0;
		// track the past coordinates of each firework to create a trail effect, increase the coordinate count to create more prominent trails
		this.coordinates = [];
		this.coordinateCount = 3;
		// populate initial coordinate collection with the current coordinates
		while( this.coordinateCount-- ) {
			this.coordinates.push( [ this.x, this.y ] );
		}
		this.angle = Math.atan2( ty - sy, tx - sx );
		this.speed = 2;
		this.acceleration = 1.05;
		this.brightness = random( 50, 70 );
		// circle target indicator radius
		this.targetRadius = 1;
	}

	// update firework
	Firework.prototype.update = function( index ) {
		// remove last item in coordinates array
		this.coordinates.pop();
		// add current coordinates to the start of the array
		this.coordinates.unshift( [ this.x, this.y ] );
		
		// cycle the circle target indicator radius
		if( this.targetRadius < 8 ) {
			this.targetRadius += 0.3;
		} else {
			this.targetRadius = 1;
		}
		
		// speed up the firework
		this.speed *= this.acceleration;
		
		// get the current velocities based on angle and speed
		var vx = Math.cos( this.angle ) * this.speed,vy = Math.sin( this.angle ) * this.speed;
		// how far will the firework have traveled with velocities applied?
		this.distanceTraveled = calculateDistance( this.sx, this.sy, this.x + vx, this.y + vy );
		
		// if the distance traveled, including velocities, is greater than the initial distance to the target, then the target has been reached
		if( this.distanceTraveled >= this.distanceToTarget ) {
			createParticles( this.tx, this.ty );
			// remove the firework, use the index passed into the update function to determine which to remove
			fireworks.splice( index, 1 );
		} else {
			// target not reached, keep traveling
			this.x += vx;
			this.y += vy;
		}
	}

	// draw firework
	Firework.prototype.draw = function() {
		ctx.beginPath();
		// move to the last tracked coordinate in the set, then draw a line to the current x and y
		ctx.moveTo( this.coordinates[ this.coordinates.length - 1][ 0 ], this.coordinates[ this.coordinates.length - 1][ 1 ] );
		ctx.lineTo( this.x, this.y );
		ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';
		ctx.stroke();
		
		ctx.beginPath();
		// draw the target for this firework with a pulsing circle
		ctx.arc( this.tx, this.ty, this.targetRadius, 0, Math.PI * 2 );
		ctx.stroke();
	}

	// create particle
	function Particle( x, y ) {
		this.x = x;
		this.y = y;
		// track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails
		this.coordinates = [];
		this.coordinateCount = 5;
		while( this.coordinateCount-- ) {
			this.coordinates.push( [ this.x, this.y ] );
		}
		// set a random angle in all possible directions, in radians
		this.angle = random( 0, Math.PI * 2 );
		this.speed = random( 1, 10 );
		// friction will slow the particle down
		this.friction = 0.95;
		// gravity will be applied and pull the particle down
		this.gravity = 1;
		// set the hue to a random number +-20 of the overall hue variable
		this.hue = random( hue - 20, hue + 20 );
		this.brightness = random( 50, 80 );
		this.alpha = 1;
		// set how fast the particle fades out
		this.decay = random( 0.015, 0.03 );
	}

	// update particle
	Particle.prototype.update = function( index ) {
		// remove last item in coordinates array
		this.coordinates.pop();
		// add current coordinates to the start of the array
		this.coordinates.unshift( [ this.x, this.y ] );
		// slow down the particle
		this.speed *= this.friction;
		// apply velocity
		this.x += Math.cos( this.angle ) * this.speed;
		this.y += Math.sin( this.angle ) * this.speed + this.gravity;
		// fade out the particle
		this.alpha -= this.decay;
		
		// remove the particle once the alpha is low enough, based on the passed in index
		if( this.alpha <= this.decay ) {
			particles.splice( index, 1 );
		}
	}

	// draw particle
	Particle.prototype.draw = function() {
		ctx. beginPath();
		// move to the last tracked coordinates in the set, then draw a line to the current x and y
		ctx.moveTo( this.coordinates[ this.coordinates.length - 1 ][ 0 ], this.coordinates[ this.coordinates.length - 1 ][ 1 ] );
		ctx.lineTo( this.x, this.y );
		ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';
		ctx.stroke();
	}

	// create particle group/explosion
	function createParticles( x, y ) {
		// increase the particle count for a bigger explosion, beware of the canvas performance hit with the increased particles though
		var particleCount = 30;
		while( particleCount-- ) {
			particles.push( new Particle( x, y ) );
		}
	}

	// main demo loop
	function loop() {
		// this function will run endlessly with requestAnimationFrame
		requestAnimFrame( loop );
		
		// increase the hue to get different colored fireworks over time
		hue += 0.5;
		
		// normally, clearRect() would be used to clear the canvas
		// we want to create a trailing effect though
		// setting the composite operation to destination-out will allow us to clear the canvas at a specific opacity, rather than wiping it entirely
		ctx.globalCompositeOperation = 'destination-out';
		// decrease the alpha property to create more prominent trails
		ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
		ctx.fillRect( 0, 0, cw, ch );
		// change the composite operation back to our main mode
		// lighter creates bright highlight points as the fireworks and particles overlap each other
		ctx.globalCompositeOperation = 'lighter';
		
		// loop over each firework, draw it, update it
		var i = fireworks.length;
		while( i-- ) {
			fireworks[ i ].draw();
			fireworks[ i ].update( i );
		}
		
		// loop over each particle, draw it, update it
		var i = particles.length;
		while( i-- ) {
			particles[ i ].draw();
			particles[ i ].update( i );
		}
		
		// launch fireworks automatically to random coordinates, when the mouse isn't down
		if( timerTick >= timerTotal ) {
			if( !mousedown ) {
				// start the firework at the bottom middle of the screen, then set the random target coordinates, the random y coordinates will be set within the range of the top half of the screen
				fireworks.push( new Firework( cw / 2, ch, random( 0, cw ), random( 0, ch / 2 ) ) );
				timerTick = 0;
			}
		} else {
			timerTick++;
		}
		
		// limit the rate at which fireworks get launched when mouse is down
		if( limiterTick >= limiterTotal ) {
			if( mousedown ) {
				// start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target
				fireworks.push( new Firework( cw / 2, ch, mx, my ) );
				limiterTick = 0;
			}
		} else {
			limiterTick++;
		}
	}

	// mouse event bindings
	// update the mouse coordinates on mousemove
	canvas.addEventListener( 'mousemove', function( e ) {
		mx = e.pageX - canvas.offsetLeft;
		my = e.pageY - canvas.offsetTop;
	});

	// toggle mousedown state and prevent canvas from being selected
	canvas.addEventListener( 'mousedown', function( e ) {
		e.preventDefault();
		mousedown = true;
	});

	canvas.addEventListener( 'mouseup', function( e ) {
		e.preventDefault();
		mousedown = false;
	});

	// once the window loads, we are ready for some fireworks!
	window.onload = loop;
  1. 雪花特效
    [随机出现雪花飘落]
/* 雪花特效 
	来自:https://blog.csdn.net/buyueliuying/article/details/78797726
	http://www.schillmania.com/projects/snowstorm/	
*/
	(function($){  
		$.fn.snow = function(options){  
		var $flake = $('<div/>').css({'position': 'absolute','z-index':'9999', 'top': '-50px'}).html('❄'),  
		documentHeight  = $(document).height(),
		documentWidth   = $(document).width(),  
		defaults = {  
			minSize     : 10,  
			maxSize     : 20,  
			newOn       : 1000,  
			flakeColor  : "#AFDAEF" /* 雪花颜色 */
		},
		options = $.extend({}, defaults, options);
		endPositionTop = documentHeight - documentHeight * 0.3;
		var interval= setInterval( function(){
		var startPositionLeft = Math.random() * documentWidth - 100,  
		startOpacity = 0.5 + Math.random(),  
		sizeFlake = options.minSize + Math.random() * options.maxSize,  
		endPositionLeft = startPositionLeft - 500 + Math.random() * 500,  
		durationFall = documentHeight * 10 + Math.random() * 5000;  
		$flake.clone().appendTo('body').css({  
			left: startPositionLeft,  
			opacity: startOpacity,
			'font-size': sizeFlake,
			color: options.flakeColor  
		}).animate({  
			top: endPositionTop,  
			left: endPositionLeft,  
			opacity: 0.2  
		},durationFall,'linear',function(){  
			$(this).remove()
		});  
		}, options.newOn);  
		};  
	})(jQuery);  
	$(function(){  
		$.fn.snow({
			minSize: 10, /* 定义雪花最小尺寸 */  
			maxSize: 45,/* 定义雪花最大尺寸 */  
			newOn: 3000  /* 定义密集程度,数字越小越密集,cup使用率越高,建议最高设置成3000 */
		});  
	});
  1. 鼠标特效
    [点击右键,出校粒子迸溅效果]
/*
来自:https://blog-static.cnblogs.com/files/graytido/cursor-effects.js
*/
class Circle {
  constructor({ origin, speed, color, angle, context }) {
    this.origin = origin
    this.position = { ...this.origin }
    this.color = color
    this.speed = speed
    this.angle = angle
    this.context = context
    this.renderCount = 0
  }

  draw() {
    this.context.fillStyle = this.color
    this.context.beginPath()
    this.context.arc(this.position.x, this.position.y, 2, 0, Math.PI * 2)
    this.context.fill()
  }

  move() {
    this.position.x = (Math.sin(this.angle) * this.speed) + this.position.x
    this.position.y = (Math.cos(this.angle) * this.speed) + this.position.y + (this.renderCount * 0.3)
    this.renderCount++
  }
}

class Boom {
  constructor ({ origin, context, circleCount = 10, area }) {
    this.origin = origin
    this.context = context
    this.circleCount = circleCount
    this.area = area
    this.stop = false
    this.circles = []
  }

  randomArray(range) {
    const length = range.length
    const randomIndex = Math.floor(length * Math.random())
    return range[randomIndex]
  }

  randomColor() {
    const range = ['8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    return '#' + this.randomArray(range) + this.randomArray(range) + this.randomArray(range) + this.randomArray(range) + this.randomArray(range) + this.randomArray(range)
  }

  randomRange(start, end) {
    return (end - start) * Math.random() + start
  }

  init() {
    for(let i = 0; i < this.circleCount; i++) {
      const circle = new Circle({
        context: this.context,
        origin: this.origin,
        color: this.randomColor(),
        angle: this.randomRange(Math.PI - 1, Math.PI + 1),
        speed: this.randomRange(1, 6)
      })
      this.circles.push(circle)
    }
  }

  move() {
    this.circles.forEach((circle, index) => {
      if (circle.position.x > this.area.width || circle.position.y > this.area.height) {
        return this.circles.splice(index, 1)
      }
      circle.move()
    })
    if (this.circles.length == 0) {
      this.stop = true
    }
  }

  draw() {
    this.circles.forEach(circle => circle.draw())
  }
}

class CursorSpecialEffects {
  constructor() {
    this.computerCanvas = document.createElement('canvas')
    this.renderCanvas = document.createElement('canvas')

    this.computerContext = this.computerCanvas.getContext('2d')
    this.renderContext = this.renderCanvas.getContext('2d')

    this.globalWidth = window.innerWidth
    this.globalHeight = window.innerHeight

    this.booms = []
    this.running = false
  }

  handleMouseDown(e) {
    const boom = new Boom({
      origin: { x: e.clientX, y: e.clientY },
      context: this.computerContext,
      area: {
        width: this.globalWidth,
        height: this.globalHeight
      }
    })
    boom.init()
    this.booms.push(boom)
    this.running || this.run()
  }

  handlePageHide() {
    this.booms = []
    this.running = false
  }

  init() {
    const style = this.renderCanvas.style
    style.position = 'fixed'
    style.top = style.left = 0
    style.zIndex = '999999999999999999999999999999999999999999'
    style.pointerEvents = 'none'

    style.width = this.renderCanvas.width = this.computerCanvas.width = this.globalWidth
    style.height = this.renderCanvas.height = this.computerCanvas.height = this.globalHeight

    document.body.append(this.renderCanvas)

    window.addEventListener('mousedown', this.handleMouseDown.bind(this))
    window.addEventListener('pagehide', this.handlePageHide.bind(this))
  }

  run() {
    this.running = true
    if (this.booms.length == 0) {
      return this.running = false
    }

    requestAnimationFrame(this.run.bind(this))

    this.computerContext.clearRect(0, 0, this.globalWidth, this.globalHeight)
    this.renderContext.clearRect(0, 0, this.globalWidth, this.globalHeight)

    this.booms.forEach((boom, index) => {
      if (boom.stop) {
        return this.booms.splice(index, 1)
      }
      boom.move()
      boom.draw()
    })
    this.renderContext.drawImage(this.computerCanvas, 0, 0, this.globalWidth, this.globalHeight)
  }
}

const cursorSpecialEffects = new CursorSpecialEffects()
cursorSpecialEffects.init()
  1. 鼠标特效
    [点击出现文字]
/* 
鼠标特效
轉自:https://www.cnblogs.com/Trojan00/p/9497509.html
*/
var a_idx = 0;
jQuery(document).ready(function($) {
	$("body").click(function(e) {
		var a = new Array("❤富强❤","❤民主❤","❤文明❤","❤和谐❤","❤自由❤","❤平等❤","❤公正❤","❤法治❤","❤爱国❤","❤敬业❤","❤诚信❤","❤友善❤");
		var $i = $("<span></span>").text(a[a_idx]);
		a_idx = (a_idx + 1) % a.length;
		var x = e.pageX,
		y = e.pageY;
		$i.css({
			"z-index": 999999999999999999999999999999999999999999999999999999999999999999999,
			"top": y - 20,
			"left": x,
			"position": "absolute",
			"font-weight": "bold",
			"color": "rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"
		});
		$("body").append($i);
		$i.animate({
			"top": y - 180,
			"opacity": 0
		},
		1500,
		function() {
			$i.remove();
		});
	});
});
  1. 鼠标特效
    [动态背景线条跟随鼠标移动]
/*动态背景线条跟随鼠标移动 
来自:https://www.cnblogs.com/Trojan00/p/9497509.html
*/	
!function(){
	function n(n,e,t){
		return n.getAttribute(e)||t
	} 
	function e(n){
		return document.getElementsByTagName(n)
	}
	function t(){
		var t=e("script"),o=t.length,i=t[o-1];
		return{
			l:o,z:n(i,"zIndex",-1),o:n(i,"opacity",.5),c:n(i,"color","0,0,0"),n:n(i,"count",99)
		}
	}
	function o(){
		a=m.width=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,
		c=m.height=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight
	}
	function i(){
		r.clearRect(0,0,a,c);
		var n,e,t,o,m,l;
		s.forEach(function(i,x){
			for(i.x+=i.xa,i.y+=i.ya,i.xa*=i.x>a||i.x<0?-1:1,i.ya*=i.y>c||i.y<0?-1:1,r.fillRect(i.x-.5,i.y-.5,1,1),e=x+1;e<u.length;e++)n=u[e],
			null!==n.x&&null!==n.y&&(o=i.x-n.x,m=i.y-n.y,
			l=o*o+m*m,l<n.max&&(n===y&&l>=n.max/2&&(i.x-=.03*o,i.y-=.03*m),
			t=(n.max-l)/n.max,r.beginPath(),r.lineWidth=t/2,r.strokeStyle="rgba("+d.c+","+(t+.2)+")",r.moveTo(i.x,i.y),r.lineTo(n.x,n.y),r.stroke()))
		}),
		x(i)
	}
	var a,c,u,m=document.createElement("canvas"),
	d=t(),l="c_n"+d.l,r=m.getContext("2d"),
	x=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||
	function(n){
		window.setTimeout(n,1e3/45)
	},
	w=Math.random,y={x:null,y:null,max:2e4};m.id=l,m.style.cssText="position:fixed;top:0;left:0;z-index:"+d.z+";opacity:"+d.o,e("body")[0].appendChild(m),o(),window.onresize=o,
	window.onmousemove=function(n){
		n=n||window.event,y.x=n.clientX,y.y=n.clientY
	},
	window.onmouseout=function(){
		y.x=null,y.y=null
	};
	for(var s=[],f=0;d.n>f;f++){
		var h=w()*a,g=w()*c,v=2*w()-1,p=2*w()-1;s.push({x:h,y:g,xa:v,ya:p,max:6e3})
	}
	u=s.concat([y]),
	setTimeout(function(){i()},100)
}();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值