canvas 制作表情包
canvas 制作表情包
代码如下。
1 <!DOCTYPE html> 2 3 <html> 4 <head> 5 <title>表情制作</title> 6 7 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> 8 <meta name="mobile-web-app-capable" content="yes"> 9 <meta name="apple-mobile-web-app-capable" content="yes"> 10 <style> 11 #image-container { 12 display: flex; 13 } 14 </style> 15 </head> 16 17 <body> 18 <script> 19 20 21 </script> 22 23 <div> 24 <input type="file" id="file" /> 25 </div> 26 <div id="image-container"> 27 <canvas width="500" height="500"></canvas> 28 <div> 29 <span>Top Line:</span><br/> 30 <input id="topLineText" type="text"><br/> 31 <span>Bottom Line:</span><br/> 32 <input id="bottomLineText" type="text"><br/> 33 <button id="saveBtn">Save</button> 34 </div> 35 </div> 36 <script> 37 function textChangeListener (evt) { 38 var id = evt.target.id; 39 var text = evt.target.value; 40 41 if (id == "topLineText") { 42 window.topLineText = text; 43 } else { 44 window.bottomLineText = text; 45 } 46 47 redrawMeme(window.imageSrc, window.topLineText, window.bottomLineText); 48 } 49 50 function redrawMeme(image, topLine, bottomLine) { 51 // 52 var canvas = document.querySelector('canvas'); 53 var ctx = canvas.getContext("2d"); 54 if (image != null) 55 ctx.drawImage(image, 0, 0, canvas.width, canvas.height); 56 57 // 58 ctx.font = '30pt Impact'; 59 ctx.textAlign = 'center'; 60 ctx.strokeStyle = 'black'; 61 ctx.lineWidth = 3; 62 ctx.fillStyle = 'white'; 63 64 if (topLine != null) { 65 ctx.fillText(topLine, canvas.width / 2, 40); 66 ctx.strokeText(topLine, canvas.width / 2, 40); 67 } 68 69 if (bottomLine != null) { 70 ctx.fillText(bottomLine, canvas.width / 2, canvas.height - 20); 71 ctx.strokeText(bottomLine, canvas.width / 2, canvas.height - 20); 72 } 73 } 74 75 function saveFile() { 76 window.open(document.querySelector('canvas').toDataURL()); 77 } 78 79 function handleFileSelect(evt) { 80 var canvasWidth = 500; 81 var canvasHeight = 500; 82 var file = evt.target.files[0]; 83 84 85 86 var reader = new FileReader(); 87 reader.onload = function(fileObject) { 88 var data = fileObject.target.result; 89 90 91 var image = new Image(); 92 image.onload = function() { 93 94 window.imageSrc = this; 95 redrawMeme(window.imageSrc, null, null); 96 } 97 98 99 image.src = data; 100 console.log(fileObject.target.result); 101 }; 102 reader.readAsDataURL(file) 103 } 104 105 window.topLineText = ""; 106 window.bottomLineText = ""; 107 var input1 = document.getElementById('topLineText'); 108 var input2 = document.getElementById('bottomLineText'); 109 input1.oninput = textChangeListener; 110 input2.oninput = textChangeListener; 111 document.getElementById('file').addEventListener('change', handleFileSelect, false); 112 document.querySelector('button').addEventListener('click', saveFile, false); 113 </script> 114 115 </body> 116 </html>