看到這個(gè)標(biāo)題,想必大家都有興趣的,今天給大家分享一個(gè)不正經(jīng)的輸入框。廢話少說(shuō),先上效果
代碼奉上:
騷氣的input
* {
margin: 0;
padding: 0;
}
body {
font-size: 30px;
}
canvas {
position: absolute;
top: 20px;
}
div {
width: 350px;
margin: 100px auto;
position: relative;
}
input {
width: 100%;
height: 30px;
position: absolute;
background: transparent;
border: none;
border-bottom: 2px solid #a0a0a0;
outline: none;
font-size: 30px;
}
.placeholder {
display: inline-block;
position: absolute;
top: -10px;
transition: .4s;
color: #ddd;
}
請(qǐng)輸入內(nèi)容...
var input = document.querySelector('input');
var span = document.querySelector('.placeholder');
input.addEventListener('focus', function () {
if (input.value.length <= 0) {
span.style.transform = 'scale(.8) translate(-20px,-30px)';
animate(false);
}
});
input.addEventListener('blur', function () {
if (input.value.length <= 0) {
span.style.transform = 'none';
animate(true);
}
});
function animate(isBack) {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
if (!this.border) {
this.border = 1;
input.style.borderBottom = 'none';
}
var width = canvas.width,
height = canvas.height;
var m = Math;
var scale = 50;
var ang = 0,
value = height * .6;
var deg = m.ceil(width / m.PI * 4),
k = isBack ? -12 : 12;
input.style.borderBottom = 'none';
var t = setInterval(function () {
ang += k;
context.clearRect(0, 0, width, height);
context.beginPath();
for (var i = 0; i < deg; i++) {
context.lineTo(m.PI * i / 180 * scale, .3 * m.sin(m.PI * (i - ang) / 180) * scale / 2 + value);
}
context.stroke();
if (m.abs(ang) > width) {//動(dòng)畫(huà)完成。重新繪制線條。
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, value);
context.lineTo(width, value);
context.strokeStyle = '#000';
context.stroke();
clearInterval(t);
}
}, 20);
}
不得不說(shuō),html5 canvas太棒了,給了前端充分的想像,結(jié)合數(shù)學(xué),給我們意想不到的驚喜。 運(yùn)用canvas最基礎(chǔ)的API,簡(jiǎn)單的三角函數(shù),可視化數(shù)學(xué)之美。
下面進(jìn)行技術(shù)總結(jié):
1、通過(guò)正弦曲線生成N個(gè)點(diǎn),然后通過(guò)context.lintTo把所有的點(diǎn)連接起來(lái),形成一個(gè)正弦曲線,我們都知道,正弦曲線表達(dá)式為:y = sin(x); 主的取值為[-1,1],如果我們?cè)趕in前面*一個(gè)系數(shù),比如:y=4*sin(x);則表示增大波峰。即上下擺動(dòng)的幅度增加了4倍。
2、canavs動(dòng)畫(huà)的基本原理:畫(huà)了擦,擦了再畫(huà)。
3、不要給canvas設(shè)置width,height的樣式,要用JS 動(dòng)態(tài)設(shè)置,用CSS設(shè)置的在繪制一些基本圖形的時(shí)候可能會(huì)變形,大家不妨可以試試。