离屏操作:
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隐藏;
<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>
手机扫一扫
移动阅读更方便
你可能感兴趣的文章