企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## Canvas离屏操作 ~~~ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> .canvas{ border: 1px solid red; } #offCanvas{ display: none; } </style> </head> <body> <canvas id="myCanvas" class="canvas" width="600px" height="400px"> 您的浏览器不支持canvas </canvas> <!-- 创建一个离屏Canvas --> <canvas id="offCanvas" class="canvas" width="600px" height="400px"> 您的浏览器不支持canvas </canvas> <script type="text/javascript"> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); var offCanvas = document.getElementById("offCanvas"); var offCtx = offCanvas.getContext("2d"); //把一些复杂的绘画操作,放在离屏Canvas上 var drawAlot = function() { for(var k = 0; k < 20; k++){ for(var i = 0; i < offCanvas.width; i+=10) { for(var j = 0; j < offCanvas.height; j+=10) { offCtx.beginPath(); offCtx.arc(i, j ,5, 0, 2*Math.PI, true); offCtx.stroke(); } } } } var posx = 0; var posy = 0; var dir = 1; var isMouseInRect = false; canvas.onmousemove = function(e) { console.log(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(); //真正要用到复杂的绘画的时候,从离屏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> ~~~