有个一需求,需要利用canvas在页面做出几个齿轮滚动的动画。具体实现思想如下:
1、由于页面有多个齿轮,必须一次画出多个齿轮,不能分开画图。
2、齿轮每转一次,对于canvas来说就是一次重绘。
代码如下
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #canvas { margin: 0; padding: 0; } * { margin: 0; padding: 0; } </style> </head> <body> <canvas id="canvas" width="667" height="375"></canvas> <script> var canvas = document.querySelector('#canvas'); var context = canvas.getContext('2d'); var back = new Image(), wheel1 = new Image(), wheel2 = new Image(), wheel3 = new Image(), wheel4 = new Image(), wheel5 = new Image(), wheel6 = new Image(), wheel7 = new Image(), wheel8 = new Image(),title = new Image(),desc = new Image(); var k = 0; back.src = './images/beginBack.jpg'; wheel1.src = './images/s_gear3.png'; wheel2.src = './images/n_gear2.png'; wheel3.src = './images/wheel_right_top1.png'; wheel4.src = './images/n_gear1.png'; wheel5.src = './images/n_gear4.png'; wheel6.src = './images/n_gear3.png'; wheel7.src = './images/s_gear2.png'; wheel8.src = './images/s_gear1.png'; title.src = './images/startTitle.png'; desc.src = './images/desc.png'; function drawImg(data) { context.clearRect(0, 0, canvas.width, canvas.height);//先清掉画布上的内容 context.drawImage(back, 0, 0); context.drawImage(desc,canvas.width / 2 - desc.width * .6 / 2,300,desc.width * .6,desc.height * .6); context.drawImage(title,canvas.width / 2 - title.width * .6 / 2,canvas.height / 2 - title.height * .6 / 2,title.width * .6,title.height * .6); for (var i = 0; i < data.length; i++) { context.save();//保存初始的状态 context.translate(data[i].x, data[i].y);//改变图片画入的起始点 context.rotate(data[i].direction * k * Math.PI / 180);//对画布进行旋转 context.drawImage(data[i].obj, 0, 0, data[i].obj.width, data[i].obj.height, -data[i].obj.width * .6 / 2, -data[i].obj.height * .6 / 2, data[i].obj.width * .6, data[i].obj.height * .6);//绘制图片 context.restore();//还原之前的状态,主要是回复绘画的起始点 } } window.onload = function () {//图片加载完毕 var data = [ { x: 660, y: 370, direction: 1, angle: 5, obj: wheel1, }, { x: 580, y: 300, direction: -1, angle: 5, obj: wheel2, }, { x: 670, y: 100, direction: 1, angle: 5, obj: wheel3, }, { x: 580, y: 50, direction: -1, angle: 5, obj: wheel4, }, { x: 200, y: 330, direction: -1, angle: 5, obj: wheel5, }, { x: -10, y: 300, direction: 1, angle: 5, obj: wheel7, }, { x:100, y: 440, direction: -1, angle: 5, obj: wheel6, }, { x: 150, y: 60, direction: 1, angle: 5, obj: wheel8, }, ]; function f() { drawImg(data); k += 1; requestAnimationFrame(f); } f(); }; </script> </body> </html>