瞎整本来是要点击编辑多张图片的,没想到弄成这样。这不是电视剧里的降龙十八掌吗
特此记录留着以后用,看来canvas做游戏特效都不错啊。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body,div{ margin:0; padding:0; } #d1{ 500px; height: 400px; border: 2px solid #00FFD1; } </style> </head> <body> <script src="js/jquery-3.3.1.min.js"></script> <div id="d1"> <canvas id="myCanvas" width="500" height="400"> <p>您的系统不支持此程序!</p> </canvas> </div> <img src="images/boss.png" alt="test01" id="img01" /> <img src="images/weixin.png" alt="test01" id="img02" /> <script> var canva=document.getElementById("myCanvas"); var cansText=canva.getContext("2d"); var imgs=new Array("images/boss.png","images/weixin.png"); var img; var draw=new Array(); var i=0; $('#img01').on('click', function(){ cansText.save(); cansText.beginPath(); img = new Image(); img.src=imgs[0]; cansText.drawImage(img,50,60,150,100); cansText.closePath(); cansText.fill(); cansText.restore(); }); $('#img02').on('click', function(){ cansText.save(); cansText.beginPath(); img = new Image(); img.src=imgs[1]; cansText.drawImage(img,60,50,150,100); cansText.closePath(); cansText.fill(); cansText.restore(); }); ini(); function ini(){ img = new Image(); img.src=imgs[0]; draw[i]=img; cansText.drawImage(draw[i],50,50,150,100); } //在事件外声明需要用到的变量 let ax,ay,x,y; canva.onmousedown=function (e) { canva.onmousemove = function(e){ x= e.clientX;y=e.clientY; //限制移动不能超出画布 (x<173)? ax=75 : ax=425; (y<148)? ay=50 : ay=350; (x < 425 && x >75)? x =e.clientX : x =ax; (y > 50 && y <350) ? y=e.clientY : y=ay; //先清除之前的然后重新绘制,关键 // cansText.clearRect(0,0,canva.width,canva.height); cansText.drawImage(img,x-75,y-50,150,100); }; canva.onmouseup = function(){ canva.onmousemove = null; canva.onmouseup = null; }; } </script> </body> </html>