步驟javascript
預覽地址: https://young-cowboy.github.io/gallery/filter_image/index.htmlcss
<!DOCTYPE html> <html> <head> <title>Filter Image</title> <style type="text/css"> *{margin: 0px;padding: 0px;} body{ padding: 50px; } img{ width: 200px; height: 200px; margin-bottom: 10px; margin-right: 10px; } #gallery{ display: flex; flex-direction: row; flex-wrap: wrap; } </style> <script type="text/javascript" src="./effect.js"></script> </head> <body> <div id="source"></div> <div id="gallery"></div> <script type="text/javascript"> var source = document.getElementById('source'); var gallery = document.getElementById('gallery'); var url = 'https://img.alicdn.com/tfs/TB1vIhSQXXXXXXFaXXXXXXXXXXX-1376-1366.png_200x200.jpg'; var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'blob'; // 指定下載類型 xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4 && xhr.status == 200){ var image = new Image(); // 建立圖片連接 image.src = URL.createObjectURL(xhr.response); image.onload = function (){ var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); canvas.width = 200; canvas.height = 200; ctx.drawImage(image, 0, 0); // 獲取圖片的RGBA數據 var canvasData = ctx.getImageData(0, 0, 200, 200); // 遍歷濾鏡算法 Object.keys(effect).forEach(function (key){ var image = filterImage(key, canvasData); gallery.appendChild(image); }); }; source.appendChild(image); } // 添加文字 function fillText(ctx, text){ ctx.font = "20px Arial"; ctx.fillStyle = "#ffffff"; ctx.shadowColor = "#000000"; ctx.shadowBlur = 10; ctx.textAlign = "center"; ctx.fillText(text, 100, 180); } // 處理RGBA function filterImage(type, canvasData){ var image = new Image(); var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); var filter = effect[type]; canvas.width = 200; canvas.height = 200; ctx.putImageData(filter(canvasData), 0, 0); fillText(ctx, type); image.src = canvas.toDataURL(); return image; } } </script> </body> </html>
濾鏡算法effect.js:https://young-cowboy.github.io/gallery/filter_image/effect.jshtml