目前幅骄,掃一掃的應(yīng)用廣泛展哭,越來(lái)越多的產(chǎn)品需要我們程序員展示二維碼,下面介紹一下怎么生成鏈接的動(dòng)態(tài)二維碼椎麦。(總是想著怎么開(kāi)始第一篇博客)
下載一個(gè)插件js (qrcode.js)
同時(shí)在頁(yè)面上設(shè)置一個(gè)隱藏域宰僧,隱藏域的value放上二維碼想展示的鏈接
這個(gè)鏈接如果很長(zhǎng)的話(huà)需要先轉(zhuǎn)成短地址,短地址的接口下篇文章再介紹观挎。
? ??functionmakeCode(){
? ??????varelText =document.getElementById("shareUrl");
? ??????if(!elText.value) {
????? ??alert("Input a text");
? ? ??? ??? elText.focus();
? ??????return;
?? ???? }
? ??? ??qrcode.makeCode(elText.value);
? ??}
document.getElementById(“shareUrl”),就是上面隱藏域的id嘁捷。
頁(yè)面上寫(xiě)一個(gè)div造成,用來(lái)展示二維碼
插件會(huì)生成canvas和img兩個(gè)標(biāo)簽,自動(dòng)加到到qrcode中普气。
varqrcode =newQRCode(document.getElementById("qrcode"), {
width:80,
height:80
? ? });
? ? makeCode();
$("#url").on("blur",function(){
? ? ? ? makeCode();
}).on("keydown",function(e){
if(e.keyCode ==13) {
? ? ? ? ? ? makeCode();
? ? ? ? }
? ? });
我在使用過(guò)程中發(fā)現(xiàn)谜疤,部分安卓機(jī)二維碼顯示有問(wèn)題特別小,并沒(méi)有按照我們?cè)O(shè)置的css顯示现诀,經(jīng)過(guò)不停地調(diào)試夷磕,我發(fā)現(xiàn)是安卓的環(huán)境下,生成的img標(biāo)簽display沒(méi)有block出來(lái)仔沿,反而canvas標(biāo)簽block出來(lái)了坐桩。只要我們通過(guò)f12肯定會(huì)發(fā)現(xiàn),正常的機(jī)子封锉,都是img標(biāo)簽block绵跷,canvas標(biāo)簽是none膘螟。所以只要我們給canvas通過(guò)js動(dòng)態(tài)的加上和img相同的class,或者相同的樣式即可碾局。具體代碼如下荆残,將原來(lái)的makeCode方法替換:
functionmakeCode(){
varelText =document.getElementById("shareUrl");
if(!elText.value) {
alert("Input a text");
? ? ? ? ? ? elText.focus();
return;
? ? ? ? }
? ? ? ? qrcode.makeCode(elText.value);
$("#qrcode img").addClass("qrimg");
$("#qrcode canvas").addClass("qrimg");
? ? }
qrimg的樣式,可根據(jù)自己實(shí)際展示效果寫(xiě):
.qrbox .qrimg {
? ? color: #999;
? ? font-size: 0.2rem;
? ? width: 100%;
? ? height: 100%;
? ? position: absolute;
}
顯示完美净当,所有機(jī)型都正常顯示了内斯,正當(dāng)我們高興的發(fā)布了,又有人發(fā)現(xiàn)像啼,安卓機(jī)又出現(xiàn)問(wèn)題了俘闯,簡(jiǎn)直就是開(kāi)發(fā)的噩夢(mèng)。忽冻。真朗。
這次的問(wèn)題是安卓機(jī)在微信環(huán)境下,沒(méi)辦法識(shí)別圖中二維碼僧诚,只能先截圖遮婶,在識(shí)別圖中的二維碼,探索的過(guò)程不說(shuō)了振诬,最后是繼續(xù)改造makeCode方法蹭睡,見(jiàn)下:
functionmakeCode(){
varelText =document.getElementById("shareUrl");
if(!elText.value) {
alert("Input a text");
? ? ? ? ? ? elText.focus();
return;
? ? ? ? }
? ? ? ? qrcode.makeCode(elText.value);
$("#qrcode img").addClass("qrimg");
$("#qrcode canvas").addClass("qrimg");
if(!$("#qrcode img").attr("src")){
$("#qrcode img").show();
$("#qrcode canvas").hide();
varcanvas = $("#qrcode canvas")[0];
vardataURL = canvas.toDataURL("image/png");
$("#qrcode img").attr("src",dataURL);
? ? ? ? }
? ? }
將canvas轉(zhuǎn)成img格式的base64碼,到現(xiàn)在赶么,一切ok肩豁。