特效描述:html5 canvas 正弦波动动画特效。html5 canvas基于css3设置正弦波数值,弧形波动动画特效。
代码结构
1. HTML代码
Amplitude
Wave length
Frequency
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var amplitudeRange = document.getElementById('amplitude');
var waveLegthRange = document.getElementById('wavelength');
var frequencyRange = document.getElementById('frequency');
var posX = 0;
var posY = 0;
var diffX = 0;
updateCanvas();
var amplitude = Number(amplitudeRange.value);
var frames = 0;
var frequency = Number(frequencyRange.value);
var wavelength = Number(waveLegthRange.value);
amplitudeRange.addEventListener('change', function (evt) {
amplitude = Number(evt.currentTarget.value);
});
waveLegthRange.addEventListener('change', function (evt) {
wavelength = Number(evt.currentTarget.value);
});
frequencyRange.addEventListener('change', function (evt) {
frequency = Number(evt.currentTarget.value);
});
animate();
window.addEventListener('resize', onResize);
function updateCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight / 2;
diffX = canvas.width / 2.5;
posX = canvas.width * .5;
posY = canvas.height * .5;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = '#f1ff22';
ctx.lineWidth = 1;
ctx.moveTo(posX, posY);
}
function drawCircle(x, y, ctx) {
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = ctx.strokeStyle;
ctx.fill();
ctx.lineWidth = 5;
ctx.stroke();
}
function calcPosY(x) {
return Math.sin((x / wavelength * (Math.PI * 2)) + frames / frequency) * amplitude;
}
function animate() {
frames++
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.lineWidth = 1;
for (var x = posX - diffX; x < canvas.width / 2 + diffX; x++) {
var y = calcPosY(x);
ctx.lineTo(x, y + posY);
}
ctx.stroke();
for (var cx = posX - diffX; cx < canvas.width / 2 + diffX; cx += 15) {
var y1 = calcPosY(cx);
drawCircle(cx, y1 + posY - 40, ctx);
}
requestAnimationFrame(animate.bind(this));
}
function onResize() {
updateCanvas();
}