qrcodeCtrl.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. app.controller('qrCodeCtrl', ['$scope', '$http', '$timeout', '$q', 'toaster', function ($scope, $http, $timeout, $q, toaster) {
  2. moment.locale('zh-cn');
  3. function initColorPicker(initColor) {
  4. var colorPicker;
  5. if (window.Pickr) {
  6. colorPicker = Pickr.create({
  7. el: '#colorPicker',
  8. default: initColor || '#000',
  9. swatches: [
  10. '#000',
  11. '#fff',
  12. 'rgb(233, 30, 99)',
  13. 'rgb(244, 67, 54)',
  14. 'rgb(233, 30, 99)',
  15. 'rgb(156, 39, 176)',
  16. 'rgb(103, 58, 183)',
  17. 'rgb(63, 81, 181)',
  18. 'rgb(33, 150, 243)',
  19. 'rgb(3, 169, 244)',
  20. 'rgb(0, 188, 212)',
  21. 'rgb(0, 150, 136)',
  22. 'rgb(76, 175, 80)',
  23. 'rgb(255, 235, 59)',
  24. 'rgb(255, 193, 7)'
  25. ],
  26. components: {
  27. preview: true,
  28. opacity: true,
  29. hue: true,
  30. interaction: {
  31. rgba: true,
  32. hex: true,
  33. hsva: true,
  34. input: true,
  35. save: true
  36. }
  37. },
  38. strings: {
  39. save: '确定',
  40. }
  41. });
  42. colorPicker.on('save', function (args) {
  43. $scope.condition.labelColor = args.toRGBA().toString()
  44. $scope.$apply()
  45. })
  46. }
  47. }
  48. //圆角矩形
  49. CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
  50. if (w < 2 * r) r = w / 2;
  51. if (h < 2 * r) r = h / 2;
  52. this.beginPath();
  53. this.moveTo(x + r, y);
  54. this.arcTo(x + w, y, x + w, y + h, r);
  55. this.arcTo(x + w, y + h, x, y + h, r);
  56. this.arcTo(x, y + h, x, y, r);
  57. this.arcTo(x, y, x + w, y, r);
  58. this.closePath();
  59. return this;
  60. };
  61. var defaultCondition = {
  62. width: 200,//总画布宽度(有背景图时生效)
  63. height: 200,//总画布高度(有背景图时生效)
  64. qrcodeLeft: 0,//二维码位于背景left位置
  65. qrcodeTop: 0,//二维码位于背景top位置
  66. labelHeight: 30,//标签占的高度
  67. labelColor: "#000",//标签颜色
  68. size: 200,//二维码尺寸
  69. background: false,
  70. backgroundPath: "img/qrcode-back.png",
  71. backgroundScale: 100,
  72. logo: false,
  73. logoPath: "img/logo.png",
  74. logoSize: 40,
  75. domain: location.protocol + "//" + location.host,//网址,如 https://www.washpayer.com,这个可以自定义
  76. pathname: '/userLogin?l=',
  77. prefix: "",//二维码前缀,如蓝牙B开通,还有某些厂商自定义前缀
  78. dataMod: 'serial',// 默认连续serial,还有batch = logicalCode列表,换行分割
  79. start: 100,
  80. end: 200,
  81. logicalCodeList: "",
  82. subIndex: false,
  83. subStart: 1,
  84. subEnd: 40,
  85. fileName: "",
  86. fileSuffix: "jpeg",
  87. };
  88. $scope.condition = $.extend(true, {}, defaultCondition, JSON.parse(localStorage.getItem("QRCODE_CONDITION")));
  89. initColorPicker($scope.condition.labelColor)
  90. $scope.pageStatus = {
  91. progress: 0,
  92. progressShow: false,
  93. progressComplete: false
  94. }
  95. $scope.previewData = {
  96. url: ""
  97. }
  98. $scope.clickBackImgBtn = function () {
  99. }
  100. function getLogicalList() {
  101. var condition = $scope.condition;
  102. var needList = []
  103. if (condition.dataMod === 'serial') {
  104. for (var i = condition.start; i <= condition.end; i++) {
  105. needList.push(i);
  106. }
  107. } else {
  108. needList = condition.logicalCodeList.split("\n")
  109. for (var i = needList.length - 1; i >= 0; i--) {
  110. var item = needList[i];
  111. needList[i] = $.trim(item);
  112. // 去空和去重
  113. if (needList[i] === '') {
  114. // 必须倒删
  115. needList.splice(i, 1)
  116. }
  117. }
  118. // 去重复
  119. needList = needList.filter(function (item, i, self) {
  120. // 数组的indexOf是元素的全等匹配,如['1111','1'].indexOf('1')结果是1,而不是0
  121. // 当前遍历元素在整个数组中出现的index 等于 当前遍历序列,则说明这个元素是新元素 返回true(加入到新数组needList),否则false
  122. var flag = self.indexOf(item) === i
  123. return flag;
  124. })
  125. }
  126. return needList
  127. }
  128. //生成二维码
  129. function getQRCodeImageData(text, label) {
  130. var condition = $scope.condition;
  131. var size = condition.size;
  132. var labelHeight = condition.labelHeight;
  133. var logoSize = condition.logoSize;
  134. //生成二维码
  135. var qrDom = $("<div></div>");
  136. qrDom.qrcode({
  137. render: "canvas", // 渲染方式有table方式(IE兼容)和canvas方式
  138. width: size, //宽度
  139. height: size, //高度
  140. text: text, //内容
  141. typeNumber: -1,//计算模式
  142. correctLevel: 2,//二维码纠错级别
  143. background: "#ffffff",//背景颜色
  144. foreground: "#000000" //二维码颜色
  145. });
  146. var canvas = qrDom.find("canvas")[0];
  147. var context = canvas.getContext("2d");
  148. var imgData = context.getImageData(0, 0, size, size);//获取到二维码图片数据流
  149. //生成背景(用来绘制标签、背景图等)
  150. var backDom = $("<canvas></canvas>");
  151. var maxW = size;
  152. var maxH = size + labelHeight;
  153. var left = condition.qrcodeLeft;
  154. var top = condition.qrcodeTop;
  155. if (condition.background) {
  156. var backImgDom = $("#previewBackImg")[0];
  157. maxW = condition.width = backImgDom.naturalWidth * (condition.backgroundScale / 100);
  158. maxH = condition.height = backImgDom.naturalHeight * (condition.backgroundScale / 100);
  159. left = condition.qrcodeLeft;
  160. top = condition.qrcodeTop;
  161. } else {
  162. maxW = condition.width = size;
  163. maxH = condition.height = size + labelHeight;
  164. left = 0;
  165. top = 0;
  166. }
  167. backDom.attr({"width": maxW, "height": maxH});
  168. var backCanvas = backDom[0];
  169. var ctx = backCanvas.getContext("2d");
  170. //绘制背景图
  171. if (condition.background) {
  172. ctx.drawImage($("#previewBackImg")[0], 0, 0, maxW, maxH);
  173. $scope.condition.backWidth = parseInt(maxW)
  174. $scope.condition.backHeight = parseInt(maxH)
  175. }
  176. // ctx.clearRect(0, 0, size, size + labelHeight);//清空绘制标题区域
  177. ctx.putImageData(imgData, left, top);//合并二维码到带背景信息的画布
  178. if (condition.fileSuffix === 'jpeg') {
  179. //标题绘制白色背景,避免变黑色
  180. ctx.fillStyle = "#fff";
  181. ctx.fillRect(left, size + top, size, labelHeight);
  182. }
  183. //绘制标题
  184. ctx.font = "bold 24px Arial";//使用粗体,稍大的字号,否则打印出来的不清晰
  185. ctx.textAlign = "center";
  186. ctx.fillStyle = condition.labelColor;
  187. ctx.fillText(label, size / 2 + left, (size + labelHeight - 8) + top);
  188. //绘制logo
  189. if (condition.logo) {
  190. var logoBorder = 4;
  191. var centerSize = 2 * logoBorder + logoSize;
  192. //清空中心区域用来绘制logo
  193. ctx.rect((size - centerSize) / 2 + left, (size - centerSize) / 2 + top, centerSize, centerSize);
  194. ctx.fillStyle = "#fff";
  195. ctx.fill();
  196. //logo图片
  197. ctx.drawImage($("#previewLogo")[0], (size - logoSize) / 2 + left, (size - logoSize) / 2 + top, logoSize, logoSize);
  198. //边框 0.5px 修复
  199. ctx.lineWidth = 1;
  200. ctx.strokeStyle = "#aaa";
  201. ctx.roundRect((size - centerSize) / 2 + left + 0.5, (size - centerSize) / 2 + top + 0.5, centerSize, centerSize, 6).stroke();
  202. }
  203. var dataURL = backCanvas.toDataURL("image/" + condition.fileSuffix);
  204. return dataURL;
  205. }
  206. //转换base64到Blob对象,用以zip压缩
  207. function convertImgDataToBlob(base64Data, fileSuffix) {
  208. var format = "image/" + fileSuffix;
  209. var base64 = base64Data;
  210. var code = window.atob(base64.split(",")[1]);
  211. var aBuffer = new window.ArrayBuffer(code.length);
  212. var uBuffer = new window.Uint8Array(aBuffer);
  213. for (var i = 0; i < code.length; i++) {
  214. uBuffer[i] = code.charCodeAt(i) & 0xff;
  215. }
  216. var blob = null;
  217. try {
  218. blob = new Blob([uBuffer], {type: format});
  219. }
  220. catch (e) {
  221. window.BlobBuilder = window.BlobBuilder ||
  222. window.WebKitBlobBuilder ||
  223. window.MozBlobBuilder ||
  224. window.MSBlobBuilder;
  225. if (e.name == 'TypeError' && window.BlobBuilder) {
  226. var bb = new window.BlobBuilder();
  227. bb.append(uBuffer.buffer);
  228. blob = bb.getBlob("image/" + fileSuffix);
  229. }
  230. else if (e.name == "InvalidStateError") {
  231. blob = new Blob([aBuffer], {type: format});
  232. }
  233. else {
  234. }
  235. }
  236. return blob;
  237. }
  238. if (BROWSER_TYPE === 'wechat') {
  239. $scope.showOpenBrowser = true
  240. }
  241. //判断访问终端
  242. var browser = {
  243. versions: function () {
  244. var u = navigator.userAgent, app = navigator.appVersion;
  245. return {
  246. trident: u.indexOf('Trident') > -1, //IE内核
  247. presto: u.indexOf('Presto') > -1, //opera内核
  248. webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
  249. gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
  250. mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
  251. ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
  252. android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
  253. iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
  254. iPad: u.indexOf('iPad') > -1, //是否iPad
  255. webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
  256. weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
  257. qq: u.match(/\sQQ/i) == " qq" //是否QQ
  258. };
  259. }(),
  260. language: (navigator.browserLanguage || navigator.language).toLowerCase()
  261. };
  262. //点击则生成图片:生成过程很慢,生成过程中请不要改表单数据!
  263. $scope.getZip = function () {
  264. if (BROWSER_TYPE === 'wechat') {
  265. $('#browser_type_error').modal();
  266. return;
  267. }
  268. var condition = $scope.condition;
  269. var needList = getLogicalList();
  270. if (needList.length === 0) {
  271. alert('没有需要生成的二维码')
  272. return;
  273. }
  274. var hasSubIndex = condition.subIndex;
  275. var subIndex = condition.subStart;
  276. var sumCodeCount = needList.length;
  277. if (hasSubIndex) {
  278. sumCodeCount = sumCodeCount * (condition.subEnd - condition.subStart + 1);
  279. }
  280. var index = 0;// 开始生成的index = 0
  281. var zip;
  282. var mask;
  283. if (browser.versions.mobile || browser.versions.android || browser.versions.ios) {
  284. if (sumCodeCount > 100) {
  285. alert("超过100个二维码,无法正常生成。手机端一次性最多只能生成100个二维码,请修改参数减少二维码数量。");
  286. return
  287. }
  288. }
  289. $.confirm({
  290. content: "将生成二维码" + sumCodeCount + "个,确定?",
  291. buttons: {
  292. ok: {
  293. action: function () {
  294. zip = new JSZip();
  295. //重置状态
  296. $scope.pageStatus.progressComplete = false;
  297. $scope.pageStatus.progressShow = true;
  298. index = 0;
  299. run();
  300. mask = new Mask("正在生成,请稍候,请不要切换或关闭页面。").show();
  301. }
  302. },
  303. }
  304. });
  305. //使用timeout避免网页卡死
  306. function run() {
  307. $timeout(function () {
  308. if (index >= needList.length) {
  309. over();
  310. return;
  311. }
  312. var nowLogical = needList[index]
  313. var progress = Math.round(index * 100 / needList.length);//刷新进度
  314. if (progress % 2 === 0) {
  315. //控制刷新次数
  316. $scope.pageStatus.progress = progress;
  317. }
  318. var currentDomain = condition.domain;
  319. var pathname = condition.pathname;
  320. var qrcode = condition.prefix + "" + nowLogical;
  321. var url = currentDomain + pathname + qrcode;
  322. var label = qrcode;
  323. if (hasSubIndex) {
  324. label = label + "-" + subIndex;
  325. url = url + "&chargeIndex=" + subIndex
  326. }
  327. var dataURL = getQRCodeImageData(url, label);
  328. var fileContent = dataURL.split('base64,')[1];
  329. zip.file(label + "." + condition.fileSuffix, fileContent, {base64: true});
  330. // 如果子编号遍历完一轮,则逻辑码+1,然后再重置子编号
  331. if (hasSubIndex) {
  332. subIndex++;
  333. if (subIndex > condition.subEnd) {
  334. index++;
  335. subIndex = condition.subStart;
  336. }
  337. } else {
  338. // 如果没有子编号,逻辑码+1
  339. index++;
  340. }
  341. run();//继续run
  342. });
  343. }
  344. function over() {
  345. $scope.pageStatus.progressComplete = true;
  346. var fileName = condition.fileName;
  347. if (!fileName) {
  348. fileName = "逻辑码"
  349. if (condition.dataMod === 'serial') {
  350. fileName = fileName + condition.start + (condition.end === condition.start ? "" : ("-" + condition.end))
  351. } else {
  352. fileName = fileName + '批量自定义' + moment().format("YYYY-MM-DD hh_mm_ss") // 文件系统不支持:
  353. }
  354. if (condition.subIndex) {
  355. fileName = fileName + " 端口" + condition.subStart + (condition.subEnd === condition.subStart ? "" : ("-" + condition.subEnd))
  356. }
  357. }
  358. zip.generateAsync({type: "blob"}).then(function (content) {
  359. // see FileSaver.js
  360. window.saveAs && saveAs(content, fileName + ".zip")
  361. });
  362. $timeout(function () {
  363. $scope.pageStatus.progressShow = false;
  364. }, 5000);
  365. mask.remove()
  366. }
  367. };
  368. //建立一個可存取到該file的url
  369. function getObjectURL(file) {
  370. var url = null;
  371. if (window.createObjectURL != undefined) { // basic
  372. url = window.createObjectURL(file);
  373. } else if (window.URL != undefined) { // mozilla(firefox)
  374. url = window.URL.createObjectURL(file);
  375. } else if (window.webkitURL != undefined) { // webkit or chrome
  376. url = window.webkitURL.createObjectURL(file);
  377. }
  378. return url;
  379. }
  380. //预览
  381. $scope.previewQRCode = function () {
  382. var condition = $scope.condition;
  383. var currentDomain = condition.domain;
  384. var pathname = condition.pathname;
  385. var qrcode = condition.prefix + "6666";
  386. var url = currentDomain + pathname + qrcode;
  387. var label = qrcode;
  388. if (condition.subIndex) {
  389. label = label + "-" + condition.subStart;
  390. url = url + "&chargeIndex=" + condition.subStart
  391. }
  392. var dataURL = getQRCodeImageData(url, label);
  393. $("#previewImg").attr({
  394. "width": condition.width,
  395. "height": condition.height,
  396. "src": dataURL,
  397. "title": url
  398. });
  399. $scope.previewData.url = url
  400. };
  401. //缓存二维码制作方案
  402. $scope.savePlan = function () {
  403. localStorage.setItem("QRCODE_CONDITION", JSON.stringify($scope.condition));
  404. };
  405. //事件绑定
  406. $timeout(function () {
  407. // 实时刷新预览,深度监听
  408. $scope.$watch("condition", function (newValue, oldValue) {
  409. if (newValue == oldValue) {
  410. // 如果两次值相等,则不刷新视图
  411. } else {
  412. $scope.previewQRCode();
  413. }
  414. }, true);
  415. $("#backImgFile").on("change", function () {
  416. var file = this.files[0];
  417. if (!file.type.includes("image")) {
  418. toaster.pop("info", "提示", "请选择图片文件!");
  419. } else {
  420. //预览logo
  421. var objUrl = getObjectURL(file);
  422. if (objUrl) {
  423. $("#previewBackImg").attr("src", objUrl);
  424. $scope.condition.backgroundPath = objUrl
  425. }
  426. }
  427. $scope.$apply();//刷新提示和数据
  428. });
  429. $("#logoFile").on("change", function () {
  430. //change说明用户需要logo
  431. $scope.condition.logo = true;
  432. var file = this.files[0];
  433. if (!file.type.includes("image")) {
  434. toaster.pop("info", "提示", "请选择图片文件!");
  435. } else {
  436. //预览logo
  437. var objUrl = getObjectURL(file);
  438. if (objUrl) {
  439. $("#previewLogo").attr("src", objUrl);
  440. $scope.condition.logoPath = objUrl
  441. }
  442. }
  443. $scope.$apply();//刷新提示和数据
  444. });
  445. $("#previewBackImg,#previewLogo").on('load', function () {
  446. // input file 没法绑定angular,当图片加载完后手动刷新预览
  447. $scope.previewQRCode();
  448. });
  449. });
  450. }]);