1.Canvas 罕用 api
获取 2d 上下文对象
let ctx = document.getElementById("canva").getContext("2d");
globalCompositeOperation
图形组合形式的设置
ctx.globalCompositeOperation = "destination-over";//新生成的图像在上方
填充和背景
// 3.设置背景填充色和边框色ctx.fillStyle = "rgba(0,0,0,0.4)";ctx.strokeStyle = "rgba(0,153,255,0.4)";
位移
// 5.设置位移ctx.translate(150, 150);
旋转
旋转只传入一个参数:旋转的角度
// 6.1 地球旋转ctx.rotate( ((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds());
画一幅地理图
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <canvas id="canva" width="500" height="500"></canvas> </body> <script type="text/javascript"> window.onload = function () { var sun = new Image(); var earth = new Image(); var moon = new Image(); // 初始化办法 function init() { sun.src = "./sun.png"; earth.src = "./earth.png"; moon.src = "./moon.png"; window.requestAnimationFrame(draw); } function draw() { // 1.获取上下文 let ctx = document.getElementById("canva").getContext("2d"); ctx.globalCompositeOperation = "destination-over"; // 2.清空 canva ctx.clearRect(0, 0, 500, 500); // 3.设置背景填充色和边框色 ctx.fillStyle = "rgba(0,0,0,0.4)"; ctx.strokeStyle = "rgba(0,153,255,0.4)"; // 4.保留状态 ctx.save(); // 5.设置位移 ctx.translate(150, 150); // 6.地球 // 从左上角开始(0,0),先定义位移、填充、旋转,而后调用 drawImage let time = new Date(); // 6.1 地球旋转 ctx.rotate( ((2 * Math.PI) / 60) * time.getSeconds() + ((2 * Math.PI) / 60000) * time.getMilliseconds() ); // 6.2 地球位移 ctx.translate(105, 0); // 6.3 填充图形 ctx.fillRect(0, -12, 50, 24); // Shadow ctx.drawImage(earth, -12, -12); // Moon ctx.save(); ctx.rotate( ((2 * Math.PI) / 6) * time.getSeconds() + ((2 * Math.PI) / 6000) * time.getMilliseconds() ); ctx.translate(0, 28.5); ctx.drawImage(moon, -2.5, -2.5); ctx.restore(); ctx.restore(); //复原到初始的状态 // 开始画圆 ctx.beginPath(); // 画圆 ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit // 描边 ctx.stroke(); ctx.drawImage(sun, 0, 0, 300, 300); window.requestAnimationFrame(draw); } init(); }; </script></html>