canvas 水波纹

<!DOCTYPE html>
<html>
<head>
<title>canvas</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
</head>
<body>
<section class="doc doc--bg2" style=" 200px;height: 200px;margin: 0 auto;border-radius: 200px;position: relative;border:1px#efefef solid;overflow: hidden;">
<canvas id="canvas" style="position:absolute;top:0px;left:0px;z-index:1;"></canvas>
</section>

<svg width="200px" height="200px" version="1.1" xmlns="http://www.w3.org/2000/svg">
<!-- Wave -->
<g id="wave">
<path id="wave-2" fill="rgba(154, 205, 50, .8)" d="M 0 100 C 133.633 85.12 51.54 116.327 200 100 A 95 95 0 0 1 0 100 Z">
<animate dur="5s" repeatCount="indefinite" attributeName="d" attributeType="XML" values="M0 100 C90 28, 92 179, 200 100 A95 95 0 0 1 0 100 Z;
M0 100 C145 100, 41 100, 200 100 A95 95 0 0 1 0 100 Z;
M0 100 C90 28, 92 179, 200 100 A95 95 0 0 1 0 100 Z"></animate>
</path>
</g>
</svg>


<script type="text/javascript">
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = canvas.parentNode.offsetWidth;
canvas.height = canvas.parentNode.offsetHeight;


//如果浏览器支持requestAnimFrame则使用requestAnimFrame否则使用setTimeout
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
//初始角度为0
var step = 0;
//定义三条不同波浪的颜色
var lines = [
"rgba(157,192,249, 0.2)",
"rgba(0,168,255, 0.2)"];
function loop(){
ctx.clearRect(0,0,canvas.width,canvas.height);
step++;
//画3个不同颜色的矩形
for(var j = lines.length - 1; j >= 0; j--) {
ctx.fillStyle = lines[j];
//每个矩形的角度都不同,每个之间相差90度
var angle = (step+j*90)*Math.PI/180;//角度转换成弧度
var deltaHeight = Math.sin(angle) * 50;//矩形高度的变化量
var deltaHeightRight = Math.cos(angle) * 50;//矩形高度的变化量(右上顶点)
ctx.beginPath();//开始绘制路径
ctx.moveTo(0, canvas.height/2+deltaHeight);//左上角
ctx.bezierCurveTo(canvas.width /2, canvas.height/2+deltaHeight-50,//起点控制点xy
canvas.width / 2, canvas.height/2+deltaHeightRight-50, //结束点控制点xy
canvas.width, canvas.height/2+deltaHeightRight);//结束点xy
ctx.lineTo(canvas.width, canvas.height);//右下角
ctx.lineTo(0, canvas.height);////左下角
ctx.lineTo(0, canvas.height/2+deltaHeight);//左上角
ctx.closePath();//闭合路径
ctx.fill();//填充路径
}
// requestAnimFrame(loop);//动画
}
loop();


</script>
</body>
</html>
原文地址:https://www.cnblogs.com/chengyalin/p/9414052.html