1. 程式人生 > >Cordova各個外掛使用介紹系列(四)—canvas2ImagePlugin儲存二維碼到手機本地

Cordova各個外掛使用介紹系列(四)—canvas2ImagePlugin儲存二維碼到手機本地

同樣的,我還是想說,首先我這個是做基於ionic+ngCordova+Anjularjs的專案,所以,希望大家在看之前已經瞭解了這三塊內容了,不然,可能看起來會有難度的。

一、下載相關的外掛的命令:

cordova plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git

二、HTML程式碼:

 
<div class="col text-center">
    <span>(二維碼)</span>

    <div class="cro">
        <div id="Qrcode">
            <div class="cro_left_top"></div>
            <div class="cro_right_top"></div>
            <div class="cro_left_bottom"></div>
            <div class="cro_right_bottom"></div>
        </div>
        <button class="button button-positive"
                ng-click="saveImageQrcode()">儲存到手機
        </button>
    </div>
</div>

三、CSS程式碼,根據UI實現瞭如下介面的CSS程式碼:

<style type="text/css">
    .cro {
        width: 300px;
        height: 360px;
        position: relative;
        text-align: center;
        margin: auto;
        background: white;
    }

    .cro_left_top, .cro_right_top, .cro_left_bottom, .cro_right_bottom {
        position: absolute;
        width: 20px;
        height: 20px;
        z-index: 1;
        background: #212A27;
    }

    .cro_left_top {
        top: -1px;
        left: -1px;
        border-radius: 0px 0px 20px 0px;
    }

    .cro_right_top {
        top: -1px;
        right: -1px;
        border-radius: 0px 0px 0px 20px;
    }

    .cro_left_bottom {
        left: -1px;
        bottom: -1px;
        border-radius: 0px 20px 0px 0px;
    }

    .cro_right_bottom {
        right: -1px;
        bottom: -1px;
        border-radius: 20px 0px 0px 0px;
    }
</style>

四、JS程式碼如下:

var qrcode = new QRCode(document.getElementById("Qrcode"), {
    width: 200,
    height: 200
});
qrcode.makeCode("123");

var a = document.getElementById("Qrcode");
var canvas = a.children[4];
canvas.id = "myCanvas";
$scope.saveImage = canvas.toDataURL();

//呼叫儲存二維碼圖片的函式
$scope.saveImageQrcode = function () {
    console.log(window.canvas2ImagePlugin);
    window.canvas2ImagePlugin.saveImageDataToLibrary(function (msg) {
            console.log(msg);
            $rootScope.alert('圖片已儲存');
        },
        function (err) {
            console.log(err);
        },
        document.getElementById('myCanvas')
    )
};