您好,登錄后才能下訂單哦!
小編給大家分享一下JavaScript中canvas如何實現九宮格切圖效果,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
首先頁面展示
直接上代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> body { text-align: center; } canvas { border: 1px solid; } .newcanvas { width: 316px; height: 316px; margin: auto; } .newpohoto, .download { width: 300px; height: 40px; line-height: 40px; margin: auto; background-color: cornflowerblue; border-radius: 5px; cursor: pointer; margin: 10px auto; color: white; } </style> </head> <body> <h4>使用canvas實現九宮格切圖的效果</h4> <div class="mycanvas"> <canvas width="300" height="300" id="mycnavas"></canvas> </div> <div class="newpohoto"> 開始切圖 </div> <div class="newcanvas"> <canvas width="100" height="100" id="img1"></canvas> <canvas width="100" height="100" id="img2"></canvas> <canvas width="100" height="100" id="img3"></canvas> <canvas width="100" height="100" id="img4"></canvas> <canvas width="100" height="100" id="img5"></canvas> <canvas width="100" height="100" id="img6"></canvas> <canvas width="100" height="100" id="img7"></canvas> <canvas width="100" height="100" id="img8"></canvas> <canvas width="100" height="100" id="img9"></canvas> </div> <div class="download"> 下載圖片 </div> <script> var canvas = document.getElementById("mycnavas"); //現將圖片放上去 var cxt = mycnavas.getContext("2d"); var img = new Image(); img.src = "../img/img10.jpg"; window.onload = function() { cxt.drawImage(img, 0, 0, 400, 300); //畫好圖片的位置 } var arr = []; //將切的圖片存到數組里面 document.getElementsByClassName("newpohoto")[0].onclick = function() { var q = 1; for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { var data = cxt.getImageData(j * 100, i * 100, 400, 100); //類似于“復制”功能 var img = document.getElementById("img" + q) var newcxt = img.getContext("2d"); newcxt.putImageData(data, 0, 0); //類似“粘貼”功能 arr.push(console.log(img.toDataURL(q + ".png"))) //toDataURL()方法的兩個參數:DataURL(type, encoderOptions) type指定轉換為base64編碼后圖片的格式,如:image/png、image/jpeg、image/webp等等,默認為image/png格式; q++; console.log(arr) } } } //下載切的圖片 var arr = []; document.getElementsByClassName('download')[0].onclick = function() { for (var i = 0; i < 9; i++) { var a = document.createElement('a'); a.download = 'img' + (i + 1); a.href = arr[i]; document.body.appendChild(a); a.click(); } } </script> </body> </html>
看完了這篇文章,相信你對“JavaScript中canvas如何實現九宮格切圖效果”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。