vue url生产二维码

 

 

<template>
    <div id="QRcode">
       <div class='QR-qrcode' style='display:none;'></div>
    </div>
</template>
<script>

    import QRCode from 'qrcode-js-package'

    export default {
        data () {
            return {

            }
        },
        props: {
            size: {
                type: Number,
                default: 180,
            },
            value: {
                type: String,
                default: '',
            },
        },
        watch:{
            "$parent.qrText"(newVal){
                this.getQRcodeImg((base64)=>{
                    document.getElementsByClassName("QR-download")[0].href = base64 ;
                });
            },
        },
        methods: {
            concatCanvas(dom,canvas1,padding){
                /**
                 * @param {Number} padding 图片的padding,默认20
                 * @return {String} 返回base64字符串
                 *
                 */
                var c1h = canvas1.height,
                    c1w = canvas1.width,
                    context='',
                    canvas = document.createElement("canvas");
                padding = padding || 20 ;
                canvas.height = c1h + 2.5 * padding ;
                canvas.width = c1w + 2 * padding ;
                /** end **/
                dom.appendChild(canvas);
                /** 将canvas画上白色背景 **/
                context = canvas.getContext("2d");
                context.fillStyle ="white";
                context.fillRect(0,0,canvas.width,canvas.height);
                /** end **/

                context.drawImage(canvas1, padding, padding, c1w ,c1h);
                /** end **/
                /** 返回base64,用于注入到a标签里以便下载 **/
                return canvas.toDataURL('image/jpeg',1);
                /** end **/
            },
            getQRcodeImg(fn,s){
                let url = s||this.value,
                    size = this.size,
                    dom = document.getElementById("QRcode"),
                    $qrcode = dom.getElementsByClassName("QR-qrcode")[0],
                    $main = dom.getElementsByClassName("QR-main")[0];

                new QRCode($qrcode, {
                    text: url,
                    width: size,
                    height: size,
                    correctLevel : QRCode.CorrectLevel.H
                });
                let base64 = this.concatCanvas(dom,$qrcode.getElementsByTagName("canvas")[0],15);
                fn && fn(base64);
            }
        },
    }
</script>

 

结果:

 

posted @ 2018-12-01 19:34  快乐的咸鱼  阅读(1570)  评论(0编辑  收藏  举报