css:
#canvas { background-color: #eee; border-radius: 50%; } #record-btn { margin-top: 20px; padding: 10px; border-radius: 5px; background-color: #f00; color: #fff; border: none; font-size: 16px; }
HTML:
<canvas id="canvas" width="100" height="100"></canvas> <button id="record-btn">长按录制</button>
js:
<script> let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); let recordBtn = document.getElementById('record-btn'); let timer; // 用于记录计时器 let count = 10; // 计数器,初始值为10秒 // 绘制外部圆环 function drawOuterCircle() { context.lineWidth = 10; context.strokeStyle = '#ccc'; context.beginPath(); context.arc(50, 50, 40, 0, Math.PI * 2); context.stroke(); } // 绘制内部圆环 function drawInnerCircle() { context.lineWidth = 8; context.strokeStyle = '#f00'; context.lineCap = 'round'; context.beginPath(); context.arc(50, 50, 40, -Math.PI / 2, (-Math.PI / 2) + (count / 10) * Math.PI * 2); context.stroke(); } // 清除canvas画布 function clear() { context.clearRect(0, 0, canvas.width, canvas.height); } // 计时器函数 function startTimer() { timer = setTimeout(function() { if (count > 0) { clear(); count--; drawOuterCircle(); drawInnerCircle(); startTimer(); } else { stopTimer(); recordBtn.innerText = '开始录制'; // 录制结束后的操作 } }, 1000); } // 停止计时器函数 function stopTimer() { clearTimeout(timer); count = 10; clear(); drawOuterCircle(); } let isRecording = false; // 用于记录是否正在录制 recordBtn.addEventListener('mousedown', function() { if (!isRecording) { isRecording = true; recordBtn.innerText = '松开结束'; clear(); drawOuterCircle(); startTimer(); // 开始录制的操作 } }); recordBtn.addEventListener('mouseup', function() { if (isRecording) { isRecording = false; stopTimer(); recordBtn.innerText = '开始录制'; // 结束录制的操作 } }); drawOuterCircle(); </script>
现在,当长按录制按钮时,canvas上会绘制一个外部圆环,内部圆环逐渐显示,并倒计时10秒。当用户松开按钮时,计时器停止,内部圆环消失,canvas上只剩下外部圆环。