canvas_16 平移与旋转

效果图:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <style type="text/css">
 8         canvas {
 9             border: 1px solid #eee;
10         }
11     </style>
12     <body>
13         <canvas id="cvs" height="500" width="500"></canvas>
14 
15         <script type="text/javascript">
16             var canvas = document.querySelector("#cvs");
17             var ctx = canvas.getContext("2d");
18 
19             // (100, 100)坐标旋转的话
20             var deg = 0;
21             setInterval(function() {
22                 ctx.clearRect(0, 0, canvas.width, canvas.height);
23 
24                 ctx.beginPath();
25                 ctx.fillStyle = "blue";
26                 ctx.fillRect(100, 100, 100, 100);
27 
28                 ctx.beginPath();
29                 ctx.moveTo(300, 200);
30                 ctx.lineTo(350, 100);
31                 ctx.lineTo(400, 200);
32                 ctx.closePath();
33                 ctx.fill();
34                 ctx.save();
35 
36                 deg += 0.1;
37                 ctx.beginPath();
38                 // 目的坐标的中心点旋转的话
39                 ctx.translate(150, 150);
40                 ctx.rotate(deg);
41                 ctx.fillStyle = "orange";
42                 ctx.fillRect(-50, -50, 100, 100);
43                 ctx.restore();
44 
45                 ctx.save();
46                 ctx.translate(350, 100);
47                 // 绕着 translate 的点旋转
48                 ctx.rotate(deg);
49                 ctx.beginPath();
50                 ctx.moveTo(-50, 100);
51                 ctx.lineTo(0, 0);
52                 ctx.lineTo(50, 100);
53                 ctx.fillStyle = "orange";
54                 ctx.closePath();
55                 ctx.fill();
56                 ctx.restore();
57             }, 50)
58         </script>
59     </body>
60 </html>
原文地址:https://www.cnblogs.com/luwei0915/p/15776985.html