效果图:
要求:
1.点击play按钮,播放音乐,点击pause按钮停止音乐
2.点击play按钮,专辑旋转,点击pause按钮专辑停止;
实现步骤:
1.创建canvas标签,设置width,height,id;
2.获取canvas的执行上下文,贴4张图(drawImage);
2.1真正项目总图片是异步获取的,所以无法确定先后绘画顺序,但是我萌绘画就i要有先后顺序,背景先行,专辑,按钮图片要再背景之后,(肿么办),使用变量progress;每加载完成就根据大小进行增加,知道progress=100;再进行绘制
3.统一绘制,背景,专辑背景,专辑,两个按钮
html:
<h3>使用Canvas绘制音乐播放器</h3>
<canvas id="c"></canvas>
<audio src="res/bg.mp3" id="ad"></audio>
css:
<style>
body{
text-align: center;
}
#c{
background: #f0f0f0;
}
</style>
js:
<script> var cv = document.getElementById("c"); var ad = document.getElementById("ad"); // 进度 var progress = 0; var p1 = new Image(); p1.src = "img/bg.jpg"; p1.onload = function () { progress += 20; if (progress === 100) { startDraw() } } var p2 = new Image(); p2.src = "img/disc.png"; p2.onload = function () { progress += 20; if (progress === 100) { startDraw() } } var p3 = new Image(); p3.src = "img/play.png"; p3.onload = function () { progress += 20; if (progress === 100) { startDraw() } } var p4 = new Image(); p4.src = "img/pause.png"; p4.onload = function () { progress += 40; if (progress === 100) { startDraw() } }; // 不管哪个加载到了100,都可以执行startDraw函数 function startDraw() { var timer = null; var ctx = cv.getContext('2d'); //1.设置画布宽度/高度 var w = p1.width; var h = p1.height; cv.width = w; cv.height = h; ctx.drawImage(p1, 0, 0); //2.绘制专辑边框 ctx.beginPath(); ctx.arc(w / 2, h / 2, 120, 0, 2 * Math.PI); ctx.fill(); // 2.1绘制专辑, // 2.2估算内圆半径,利用外圆半径*sin(45°) var r = 120 * Math.sin(Math.PI / 4); ctx.drawImage(p2, w / 2 - r, h / 2 - r, 2 * r, 2 * r); // 3.绘制开始按钮 ctx.drawImage(p3, w / 2 - 40, h - 80, 80, 80); // 4.绘制暂停按钮 ctx.drawImage(p4, w / 2 + 40, h - 80, 80, 80); // 5绑定事件 var deg = 0; cv.onclick = function (e) { var x = e.offsetX; var y = e.offsetY; var plX = w / 2; var plY = h - 40; var paX = w / 2 + 80; var paY = h - 40; var btnR = 40; // 点击点到play或pause按钮的距离distance=//
![formula](https://i-blog.csdnimg.cn/blog_migrate/7289b0f0320a2b20f100dd20218f2672.png)
var plDistance = Math.sqrt(Math.pow((x - plX), 2) + Math.pow((y - plY), 2)); var paDistance = Math.sqrt(Math.pow((x - paX), 2) + Math.pow((y - paY), 2)); // 判断小于点击到了 if (plDistance <= btnR) { if (timer) { return } timer = setInterval(function () { deg += 1; ctx.save(); ctx.translate(w / 2, h / 2); ctx.rotate(deg * Math.PI / 180); ctx.drawImage(p2, -r, -r, 2 * r, 2 * r); ctx.restore(); ad.play(); }, 60); alert("开始了") } if (paDistance <= btnR) { if (!timer) { return } clearInterval(timer); timer = null; ad.pause() alert("暂停了") } } } </script>