var can1; var cam2; var ctx1; var ctx2; var lastTime; var deltaTime; var bgPic = new Image(); var canWidth; var canHeight; var ane; var fruit; document.body.onload = game; function game() { // body... init(); gameloop(); } function init(){ //获得canvas context can1 = document.getElementById("canvas1"); can2 = document.getElementById("canvas2"); ctx1 = can1.getContext('2d'); ctx2 = can2.getContext('2d'); bgPic.src = './src/background.jpg'; canWidth = can1.width; canHeight = can1.height; drawBackground(); ane = new aneObj(); ane.init(); fruit = new fruitObj(); fruit.init(); } function gameloop(){ //requestAnimFrame(gameloop); window.requestAnimFrame(gameloop); var now = Date.now(); deltaTime = now - lastTime; lastTime = now; ane.draw(); fruit.draw(); } var aneObj = function(){ this.x = []; this.len = []; } aneObj.prototype.num = 50; aneObj.prototype.init = function(){ for (var i = 0; i <= this.num; i++) { this.x[i] = i * 16 + Math.random() * 20; this.len[i] = 200 + Math.random() * 20; } } aneObj.prototype.draw = function(){ ctx2.save(); ctx2.globalAlpha=0.2; ctx2.lineWidth = 20; ctx2.lineCap = "round"; ctx2.strokeStyle = "#3b154e"; for (var i = 0; i < this.num; i++) { ctx2.beginPath(); ctx2.moveTo(this.x[i], canHeight); ctx2.lineTo(this.x[i], canHeight - this.len[i]); ctx2.stroke(); } ctx2.restore(); }
要在gameloop最前面加一个clearRect()重绘,不然会一直叠加就不透明了
对上面定义属性名字写错了
var can1;
var cam2;
var ctx1;
var ctx2;