離屏操作: 1.創建一個新的離屏canvas; 2.把一些復雜額繪畫操作(背景),畫在離屏canvas上; 3.將離屏canvas通過drawImage(離屏canvas對象,x1,y1,offcanvas.width,offcanvas.height,x2,y2,canvas.width,canvas.height)拷貝到原始的canvas上,減少不斷繪制復雜操作,提高性能-----最后使用css:display:none將離屏canvas隱藏;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>離屏canvas</title> <style> canvas{ border: 1px solid red; } #offCanvas{ /* display: none; */ } </style> </head> <body> <canvas id="myCanvas">您的瀏覽器不支持canvas</canvas> <canvas id="offCanvas">您的瀏覽器不支持canvas</canvas> <script> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var offCanvas = document.getElementById("offCanvas"); var offCtx = offCanvas.getContext("2d"); var posx = 0,posy = 0,dir = 1,isMouseInRect = false; var drawALot = function(){ for(var k=0;k<20;k++){ for(var i=0;i<canvas.width;i+=10){ for(var j=0;j<canvas.height;j+=10){ offCtx.beginPath(); offCtx.arc(i,j,5,0,2*Math.PI,true); offCtx.stroke(); } } } } canvas.onmousemove = function(e){ var mouseX = e.offsetX; var mouseY = e.offsetY; if(mouseX > posx && mouseX < posx + 50 && mouseY > posy && mouseY < posy +50){ isMouseInRect = true; }else{ isMouseInRect = false; } } setInterval(function(){ if(!isMouseInRect){ posx += 10 *dir; } //清空畫布區域 ctx.clearRect(0,0,canvas.width,canvas.height); //drawALot(); //使用drawImage(canvas對象)拷貝到原始canvas上 ctx.drawImage(offCanvas,0,0,offCanvas.width,offCanvas.height,0,0,canvas.width,canvas.height); ctx.fillRect(posx,posy,50,50); if(posx+50 >= canvas.width){ dir = -1; }else if(posx <=0){ dir = 1; } },100); drawALot(); </script> </body> </html>