返回列表

canvas中绘制图片源的src发生改变后,绘图会变为空白

默认分类 2015/11/07 05:45

canvas中绘制图片源的src发生改变后,绘图会变为空白

解决方法是: 先删除原来的图片,再创建一张一模一样的图片。

下面这段代码是修复后的代码

var origin = document.getElementById(pid + 'Origin');
var parentNode = origin.parentNode;
parentNode.removeChild(origin);

origin = document.createElement('img');
origin.className = 'img-origin';
origin.src = reader.result;
origin.id = pid + 'Origin';
parentNode.appendChild(origin);

其对应修复前有问题的代码如下

var origin = document.getElementById(pid + 'Origin');
origin.src = reader.result;

全部代码

<!DOCTYPE html>
<html>

<head>
<title>洋码头-上传身份证</title>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<script src="/ymt_core.69d806bac3.js"></script>
<script src="/zepto.08084123f2.js"></script>
<script type="text/javascript">
'use strict';
var hui = window.hui = window.hui ? window.hui : {};

hui.loadjs = function (url) {
    // 容错处理
    if (!url) {
        return window.console.log('hui.loadjs(url): url is null');
    }
    // 一次加载多个
    if (Object.prototype.toString.call(url) === '[object Array]') {
        for (var i = 0, len = url.length; i < len; i++) {
            hui.loadjs(url[i]);
        }
        return;
    }
    // 开始加载
    if (hui.loadjs.loaded && hui.loadjs.loaded[url]) return;
    hui.loadjs.loaded = hui.loadjs.loaded || {};
    hui.loadjs.loaded[url] = true;

    var env = 'evt';
    var s = document.createElement('script');
    url = window.location.href.indexOf('startDebug=true') !== -1 && url.indexOf('/_sourcemap.') === -1 ?
        url.replace(/\.[a-z0-9]{10}\.js/, '.js') : url;
    s.src = url + ((env === 'dev' && window.location.href.indexOf('stopDev=true') === -1) || window.location.href.indexOf('startDev=true') !== -1 ? '?' + (new Date().getTime()) : '');
    document.documentElement.appendChild(s);
};

// 本地模块及外部模块
window.sourcemap_local = window.sourcemap_local || {};
window.sourcemap_third = window.sourcemap_third || {};

// 自动加载依赖模块
hui.define_autoload = true;
hui.staticDomain = '';

// 基础模块初始化结束后的回调
hui.loadNextCallback = [];
hui.onDefineReady = function (callback) {
    (hui.loadNextLoaded ? callback() : hui.loadNextCallback.push(callback));
};

// hui.onDefineReady 示例
hui.onDefineReady(function (callback) {
    hui.showLog = function (msg, opt) {
        opt = opt || {};
        var outputlog = document.getElementById('outputlog');
        var outputlogtxt = document.getElementById('outputlogtxt');
        if (!outputlog) {
            var str = '<div id="outputlog" onclick="this.style.display=\'none\'" style="position: fixed;z-index: 2000;width: 80%;height: 80%;left: 10%;top: 5%;word-break: break-all;"></div>';
            var node = document.createElement('DIV');
            node.innerHTML = str;
            for (var i = 0, len = node.children.length; i < len; i++) {
                document.documentElement.appendChild(node.children[i]);
            }
            node = undefined;
            outputlog = document.getElementById('outputlog');
        }

        if (outputlog) {
            var outputlogtxt = outputlog.getElementsByTagName('strong')[0];
            if (outputlogtxt) {
                outputlogtxt.innerHTML = msg;
            }
            else {
                outputlog.innerHTML = ['<table style="width: 100%;height: 100%;"><tbody><tr><td style="vertical-align: middle;text-align: center;">',
                    '<strong style="font-weight:normal; display: inline-block;background-color: black;color: white;opacity: 0.75;padding: 1.5rem 1rem;border-radius: 10px;font-size: 1.3rem;">',
                    msg,
                    '</strong></td></tr></tbody></table></div>'
                ].join('');
            }
            outputlog.style.display = 'block';
        }
        if (String(opt.time) !== '-1') {
            if (outputlog.timer) {
                window.clearTimeout(outputlog.timer);
            }
            outputlog.timer = window.setTimeout(function () {
                var a = document.getElementById('outputlog');
                a && (a.style.display = 'none');
                a.timer = null;
                opt.onclose && opt.onclose();
            }, opt.time || 3000);
        }
    };
});
</script>
<script type="text/javascript">
'use strict';
(function (doc, win) {
    // 分辨率Resolution适配
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            docEl.style.fontSize = 10 * (clientWidth / 320) + 'px';
        };

    // Abort if browser does not support addEventListener
    if (!doc.addEventListener) return;
    win.addEventListener(resizeEvt, recalc, false);
    doc.addEventListener('DOMContentLoaded', recalc, false);

    // 一物理像素在不同屏幕的显示效果不一样。要根据devicePixelRatio来修改meta标签的scale,要注释上面的meta标签
    (function () {
        //return;
        var dpr = 0;
        var isIPhone = win.navigator.appVersion.match(/iphone/gi);
        var devicePixelRatio = win.devicePixelRatio;

        if (isIPhone) {
            // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
            if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
                dpr = 3;
            }
            else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)) {
                dpr = 2;
            }
            else {
                dpr = 1;
            }
        }
        else {
            // 其他设备下,仍旧使用1倍的方案
            dpr = 1;
        }

        var scale = 1 / dpr;

        // 
        var metaEl = '';
        metaEl = doc.createElement('meta');
        metaEl.setAttribute('name', 'viewport');
        metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');

        if (docEl.firstElementChild) {
            docEl.firstElementChild.appendChild(metaEl);
        }
        else {
            var wrap = doc.createElement('div');
            wrap.appendChild(metaEl);
            doc.write(wrap.innerHTML);
        }
    })();

})(document, window);
</script>

<link rel="stylesheet" href="/home.css">
<style>

</style>
</head>

<body>
    <div class="wrapper">
        <h3 class="top-title">洋码头-上传身份证</h3>
        <div class="user-tip">
            你所提供的信息均将加密,安全可靠。
            <!--a href="#description">查看详情&gt;</a-->
        </div>
        <div class="section section-first">
            <div class="section-title">收件人</div>
            <div class="section-content" id="userWrap">
                <div class="username" id="username" Name="但是" Mobile="13811111111" UserId="4085" AccessToken="276827AB97D367A6662BB8A46D4A6A828980C19A4654A5DE117CF54F3CA96BDE798AA5B04F276D9F9C27D205698F300463954DCAEA8B27DB" OrderId="" AddressId="764722">但是(联系电话:13811111111)</div>
            </div>
        </div>
        <div class="section">
            <div class="section-title">收件人身份证号</div>
            <div class="section-subtitle">务必与所选收件人相匹配</div>
            <div class="section-content">
                <input type="text" name="CardNumber" id="CardNumber" maxlength="18" class="input-text" value="">
            </div>
        </div>
        <!--div class="section">
            <button onclick="testAndroidCallback()">testAndroidCallback</button>
        </div-->
        <div class="section">
            <div class="section-title">收件人身份证照片</div>
            <div class="section-subtitle">需横屏拍摄,务必成像清晰

            </div>
            <div class="section-content">
                <div class="row">
                    <div class="cell-left">
                        <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" class="sample-front">
                        <br/>正面样例
                    </div>
                    <div class="cell-right">
                        <div class="img-add">
                            <input type="file" name="RightSide" id="RightSide" index="1" multiple123="multiple" class="file-input" ontouchend="this.onclick='';page.chooseImage(this)" onclick="page.chooseImage(this)" onchange="page.previewImage(this)" />
                            <button class="btn-add" id="RightSideBtn">选择</button>
                            <button class="btn-rotate" onclick="rotateImg('RightSide')" >转向</button>
                        </div>
                        <div class="img-front">
                            <img src="/idcard-1.jpg" alt="" class="img-upload" id="RightSidePreview" url="" />
                            <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt="" class="img-origin" id="RightSideOrigin" />
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="cell-left">
                        <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" class="sample-back">
                        <br/>背面样例
                    </div>
                    <div class="cell-right">
                        <div class="img-add">
                            <input type="file" name="ReverseSide" id="ReverseSide" index="1" multiple123="multiple" class="file-input" ontouchend="this.onclick='';page.chooseImage(this)" onclick="page.chooseImage(this)" onchange="page.previewImage(this)" />
                            <button class="btn-add" id="ReverseSideBtn">选择</button>
                            <button class="btn-rotate" onclick="rotateImg('ReverseSide')">转向</button>
                        </div>
                        <div class="img-front">
                            <img src="/idcard-2.jpg" alt="" class="img-upload" id="ReverseSidePreview" url="" />
                            <img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt="" class="img-origin" id="ReverseSideOrigin" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <canvas id="myCanvas" width="1" height="1" style="border:0px solid #c3c3c3;"></canvas>
        <div class="section-action">
            <button class="btn-upload" id="btnSubmit" onclick="page.saveIdCardInfo()">上 传</button>
        </div>
    </div>
    <script type="text/javascript">
    'use strict';
    var Ymt;
    var page = {};

    window.onload = function () {
        var RightSide = document.getElementById('RightSide');
        var ReverseSide = document.getElementById('ReverseSide');
        var RightSideBtn = document.getElementById('RightSideBtn');
        var ReverseSideBtn = document.getElementById('ReverseSideBtn');
        if (window.Ymt && Ymt.chooseImage) {
            RightSide.style.display = 'none';
            ReverseSide.style.display = 'none';
            RightSideBtn.ontouchend = RightSide.ontouchend;
            RightSideBtn.onclick = RightSide.onclick;
            ReverseSideBtn.ontouchend = ReverseSide.ontouchend;
            ReverseSideBtn.onclick = ReverseSide.onclick;
        }

        if (document.getElementById('myCanvas').getContext) {
            page.initCanvas('RightSide');
            page.initCanvas('ReverseSide');
        }


    };

    page.initCanvas = function (pid) {
        var preview = document.getElementById(pid + 'Preview');
        var fileinput = document.getElementById(pid);
        var index = parseInt(fileinput.getAttribute('index'), 10);
        var result  = document.getElementById(pid + 'Result');
        result && preview.parentNode.removeChild(result);

        result = document.createElement('canvas');
        result.setAttribute('id', pid + 'Result');
        result.className = 'img-result';
        result.width = 800;
        result.height = 600;
        preview.parentNode.insertBefore(result, preview);
        fileinput.setAttribute('index', index);
    };


    page.checkIdCardInfo = function () {
        var CardNumber = document.getElementById('CardNumber').value;
        if (!page.checkIdCode(CardNumber)) {
            hui.showLog('您输入的身份证格式有误,<br/>请确认后重新输入');
            return false;
        }
        return true;
    };
    /**
     * @method checkIdCardPhoto
     * @description 检查身份证图片
     */
    page.checkIdCardPhoto = function () {
        var RightSide = document.getElementById('RightSide');
        var ReverseSide = document.getElementById('ReverseSide');
        if ((RightSide.getAttribute('url') || (RightSide.files && RightSide.files.length)) &&
            (ReverseSide.getAttribute('url') || (ReverseSide.files && ReverseSide.files.length))) {
            return true;
        }
        hui.showLog('身份证图片不能为空');
        return false;
    };
    /**
     * @method getParamMap
     * @description 获取数据
     */
    page.getParamMap = function () {
        var username = document.getElementById('username');
        var result = {};
        result.Name = hui.Control.decode(username.getAttribute('Name') || '');
        result.Mobile = hui.Control.decode(username.getAttribute('Mobile') || '');
        result.UserId = hui.Control.decode(username.getAttribute('UserId') || '');
        result.AccessToken = hui.Control.decode(username.getAttribute('AccessToken') || '');
        result.OrderId = hui.Control.decode(username.getAttribute('OrderId') || '');
        result.AddressId = hui.Control.decode(username.getAttribute('AddressId') || '');
        result.CardNumber = document.getElementById('CardNumber').value;
        result.Status = 0; // 0:待审核
        result.HasPic = 1; // 1:有图片
        result.BuyerId = result.UserId;
        result.Operater = result.UserId;
        result.CardType = 1; // 1:身份证

        var RightSide = document.getElementById('RightSide');
        var ReverseSide = document.getElementById('ReverseSide');
        result.RightSide = RightSide.getAttribute('url');
        result.ReverseSide = ReverseSide.getAttribute('url');

        return result;
    };
    /**
     * @method saveIdCardInfo
     * @description 提交数据到服务端
     */
    page.saveIdCardInfo = function () {
        if (!document.getElementById('btnSubmit').disabled && page.checkIdCardInfo() && page.checkIdCardPhoto() && window.FormData) {
            page.updateBtnStatus('disabled');

            if (window.Ymt && Ymt.chooseImage) {
                page.saveIdCardInfoData();
            }
            else {
                if (document.getElementById('myCanvas').getContext) {
                    page.uploadBase64Image('RightSide', function (url) {
                        document.getElementById('RightSide').setAttribute('url', url);

                        page.uploadBase64Image('ReverseSide', function (url) {
                            document.getElementById('ReverseSide').setAttribute('url', url);

                            page.saveIdCardInfoData();
                        });
                    });
                }
                else {
                    page.uploadSingleImage(document.getElementById('RightSide').files[0], function (url) {
                        document.getElementById('RightSide').setAttribute('url', url);

                        page.uploadSingleImage(document.getElementById('ReverseSide').files[0], function (url) {
                            document.getElementById('ReverseSide').setAttribute('url', url);

                            page.saveIdCardInfoData();
                        });
                    });
                }

            }
        }
    };
    page.saveIdCardInfoData = function () {
        var result = page.getParamMap();

        var formData = new FormData();
        for (var i in result) {
            formData.append(i, result[i]);
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/forBuyerApp/api/saveIdCardInfo');

        // 定义上传完成后的回调函数
        xhr.onload = function (res) {
            if (xhr.status === 200) {
                var data = (new Function('return ' + res.target.responseText))();
                if (data && data.Code == 200 && data.Data && data.Data.IsSuccess) {
                    hui.showLog('身份证上传成功', {
                        time: 3000,
                        onclose: function () {
                            window.location.href = '/forBuyerApp/goOver';
                        }
                    });
                    page.updateBtnStatus();
                }
                else {
                    hui.showLog(data && data.Data && data.Data.Message ? data.Data.Message : '身份证上传失败', {
                        time: 4000
                    });
                    page.updateBtnStatus();
                }
            }
            else {
                hui.showLog('身份证上传失败', {
                    time: 4000
                });
                page.updateBtnStatus();
            }
        };
        xhr.send(formData);
    };
    // {"Msg":"上传成功","Status":200,"Result":{"idCardPic":"http://pm2.img.ymatou.com/G01/upload/product/original/M00/07/C6/rBBlD1Yxy-WANEQ2AAcEWMJPnYo454_o.jpg"} }
    page.uploadSingleImage = function (file, next) {
        var formData = new FormData();
        formData.append('idCardPic', file);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/forBuyerApp/api/saveIdCardPhoto');

        // 定义上传完成后的回调函数
        xhr.onload = function (res) {
            if (xhr.status === 200) {
                var data = (new Function('return ' + res.target.responseText))();
                if (data && data.Status === 200 && data.Result && data.Result.idCardPic) {
                    next && next(data.Result.idCardPic);
                }
                else {
                    hui.showLog('身份证上传失败,请稍后重试');
                    // next && next();
                    page.updateBtnStatus();
                }
            }
            else {
                hui.showLog('网络错误,请稍后重试');
                // next && next();
                page.updateBtnStatus();
            }
        };
        xhr.send(formData);
    };

    page.uploadBase64Image = function (pid, next) {
        var imgBase64 = document.getElementById(pid + 'Preview').src;
        var formData = new FormData();
        formData.append('idCardPicBase64', imgBase64);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/forBuyerApp/api/saveIdCardPhotoBase64');

        // 定义上传完成后的回调函数
        xhr.onload = function (res) {
            if (xhr.status === 200) {
                var data = (new Function('return ' + res.target.responseText))();
                if (data && data.Status === 200 && data.Result && data.Result.idCardPic) {
                    next && next(data.Result.idCardPic);
                }
                else {
                    hui.showLog('身份证上传失败,请稍后重试');
                    // next && next();
                    page.updateBtnStatus();
                }
            }
            else {
                hui.showLog('网络错误,请稍后重试');
                // next && next();
                page.updateBtnStatus();
            }
        };
        xhr.send(formData);
    };

    page.updateBtnStatus = function (status) {
        var disabled = status === 'disabled' ? 'disabled' : '';
        var btnSubmit = document.getElementById('btnSubmit');
        btnSubmit.disabled = disabled;
        btnSubmit.innerHTML = disabled ? '上传中...' : '上 传';
    };

    /**
     * @method previewImage
     * @description IOS下预览图片
     */
    page.previewImage = function (elem) {
        if (typeof (FileReader) === 'undefined') {
            console.log('抱歉,你的浏览器不支持 FileReader,请使用现代浏览器操作!');
        }
        else {
            var pid = elem.id;
            var file = elem.files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {

                var preview = document.getElementById(pid + 'Preview');
                preview.src = reader.result;

                var origin = document.getElementById(pid + 'Origin');
                var parentNode = origin.parentNode;
                parentNode.removeChild(origin);

                origin = document.createElement('img');
                origin.className = 'img-origin';
                origin.src = reader.result;
                origin.id = pid + 'Origin';
                parentNode.appendChild(origin);

                elem.setAttribute('choosed', '1');

            };
        }
    };
    page.uploading = false;
    page.chooseImage = function (elem) {
        if (window.Ymt && Ymt.chooseImage && !page.uploading) {
            page.uploading = true;
            window.setTimeout(function () {
                page.uploading = false;
            }, 1500);

            window.currentFile = elem.id.replace('Btn', '');
            var UserId = document.getElementById('username').getAttribute('UserId');
            Ymt.chooseImage('{url:"http://id.m.ymatou.com/forBuyerApp/api/saveIdCardPhoto", userId:"' + UserId + '"}');
        }
    };
    window.currentFile = 'RightSide';
    // {"Msg":"上传成功","Status":200,"Result":{"idCardPic":"http://pm5.img.ymatou.com/G01/upload/product/original/M00/07/B4/rBBlD1YwbpmAc9OtAAEsLR7DFbE676_o.jpg"} }

    function onCallBack(ret) {
        if (!ret) {
            return;
        }
        try {
            ret = String(ret).replace(/\\/ig, '\\\\');
            ret = JSON.parse(ret);
            if (ret && ret.Result && ret.Result.idCardPic) {
                var url = ret.Result.idCardPic;
                var previewImage = document.getElementById(window.currentFile + 'Preview');
                previewImage.src = url;

                var currentFile = document.getElementById(window.currentFile);
                currentFile.setAttribute('url', url);

                return;
            }
            hui.showLog('上传失败');
        }
        catch (e) {
            hui.showLog(e);
        }
    }
    // 测试Android下保存
    function testAndroidCallback() {
        window.Ymt = {};
        Ymt.chooseImage = 1;
        window.currentFile = 'RightSide';
        onCallBack('{"Msg":"上传成功","Status":200,"Result":{"idCardPic":"http://pm5.img.ymatou.com/G01/upload/product/original/M00/07/B4/rBBlD1YwbpmAc9OtAAEsLR7DFbE676_o.jpg"} }');
        window.currentFile = 'ReverseSide';
        onCallBack('{"Msg":"上传成功","Status":200,"Result":{"idCardPic":"http://pm5.img.ymatou.com/G01/upload/product/original/M00/07/B4/rBBlD1YwbpmAc9OtAAEsLR7DFbE676_o.jpg"} }');
    }

    /**
     * @function 解析地址栏参数
     */
    page.parseLocator = function (url) {
        url = url === null || url === undefined ? window.location.href : String(url);
        var pair,
            query = {},
            loc = '',
            args = '',
            list,
            v,
            str = url.split('#');

        if (~url.indexOf('?')) {
            // Parse ?aa=xxx
            pair = str[0].match(/^([^\?]*)(\?(.*))?$/);
            if (pair) {
                //loc = pair[1];
                args = (pair.length == 4 ? pair[3] : '') || '';
            }
            list = args ? args.split('&') : [];
            for (var i = 0, len = list.length; i < len; i++) {
                v = list[i].split('=');
                v.push('');
                query[v[0]] = decodeURIComponent(v[1]);
            }
        }

        return {
            'location': loc,
            'query': query
        };
    };
    /**
     * @class 身份证校验
     */
    page.checkIdCode = (function () {
        /** 
         * 身份证15位编码规则:dddddd yymmdd xx p  
         * dddddd:地区码  
         * yymmdd: 出生年月日  
         * xx: 顺序类编码,无法确定  
         * p: 性别,奇数为男,偶数为女 
         * <p /> 
         * 身份证18位编码规则:dddddd yyyymmdd xxx y  
         * dddddd:地区码  
         * yyyymmdd: 出生年月日  
         * xxx:顺序类编码,无法确定,奇数为男,偶数为女  
         * y: 校验码,该位数值可通过前17位计算获得 
         * <p /> 
         * 18位号码加权因子为(从右到左) Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2,1 ] 
         * 验证位 Y = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ]  
         * 校验位计算公式:Y_P = mod( ∑(Ai×Wi),11 )  
         * i为身份证号码从右往左数的 2...18 位; Y_P为脚丫校验码所在校验码数组位置 
         *  
         */

        var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]; // 加权因子  
        var ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; // 身份证验证位值.10代表X  
        function IdCardValidate(idCard) {
            idCard = idCard.replace(/ /g, '').replace(/(^\s*)|(\s*$)/g, '');
            if (idCard.length == 15) {
                return isValidityBrithBy15IdCard(idCard);
            }
            else if (idCard.length == 18) {
                var a_idCard = idCard.split(''); // 得到身份证数组  
                if (isValidityBrithBy18IdCard(idCard) && isTrueValidateCodeBy18IdCard(a_idCard)) {
                    return true;
                }
                else {
                    return false;
                }
            }
            else {
                return false;
            }
        }
        /** 
         * 判断身份证号码为18位时最后的验证位是否正确 
         * @@param a_idCard 身份证号码数组 
         * @@return 
         */
        function isTrueValidateCodeBy18IdCard(a_idCard) {
            var sum = 0; // 声明加权求和变量  
            if (a_idCard[17].toLowerCase() == 'x') {
                a_idCard[17] = 10; // 将最后位为x的验证码替换为10方便后续操作  
            }
            for (var i = 0; i < 17; i++) {
                sum += Wi[i] * a_idCard[i]; // 加权求和  
            }
            var valCodePosition = sum % 11; // 得到验证码所位置  
            if (a_idCard[17] == ValideCode[valCodePosition]) {
                return true;
            }
            else {
                return false;
            }
        }

        /** 
         * 验证18位数身份证号码中的生日是否是有效生日 
         * @@param idCard 18位书身份证字符串 
         * @@return 
         */
        function isValidityBrithBy18IdCard(idCard18) {
            var year = idCard18.substring(6, 10);
            var month = idCard18.substring(10, 12);
            var day = idCard18.substring(12, 14);
            var temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
            // 这里用getFullYear()获取年份,避免千年虫问题  
            if (temp_date.getFullYear() != parseFloat(year) || temp_date.getMonth() != parseFloat(month) - 1 || temp_date.getDate() != parseFloat(day)) {
                return false;
            }
            else {
                return true;
            }
        }
        /** 
         * 验证15位数身份证号码中的生日是否是有效生日 
         * @@param idCard15 15位书身份证字符串 
         * @@return 
         */
        function isValidityBrithBy15IdCard(idCard15) {
            var year = idCard15.substring(6, 8);
            var month = idCard15.substring(8, 10);
            var day = idCard15.substring(10, 12);
            var temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
            // 对于老身份证中的你年龄则不需考虑千年虫问题而使用getYear()方法  
            if (temp_date.getYear() != parseFloat(year) || temp_date.getMonth() != parseFloat(month) - 1 || temp_date.getDate() != parseFloat(day)) {
                return false;
            }
            else {
                return true;
            }
        }



        return function (cardId) {
            if (cardId === null || cardId === '') {
                return false;
            }
            else {
                if (!IdCardValidate(cardId)) {
                    return false;
                }
                else {
                    return true;
                }
            }
        };
    })();
    </script>
    <br/>
    <script>
    'use strict';

    function rotateImg(pid, step) {
        var elem = document.getElementById(pid);
        if (!elem.getAttribute('choosed')) return;
        var origin = document.getElementById(pid + 'Origin');
        origin.crossOrigin = '*';

        //img的高度和宽度不能在img元素隐藏后获取,否则会出错  
        step = step ? step : (origin.getAttribute('step') || 0);
        ++step && step > 3 && (step = 0);

        origin.setAttribute('step', step);
        var scene = document.getElementById(pid + 'Result');

        // //旋转角度以弧度值为参数  
        var ctx2 = scene.getContext('2d');
        ctx2.clearRect(0, 0, scene.width, scene.height);
        ctx2.save(); //保存画笔状态 


        if (step === 1) {
            ctx2.rotate(90 * Math.PI / 180);
            ctx2.drawImage(origin, 0, 0, origin.width, origin.height, 0, -scene.width, scene.height, scene.width);
        }
        else if (step === 2) {
            ctx2.rotate(180 * Math.PI / 180);
            ctx2.drawImage(origin, 0, 0, origin.width, origin.height, -scene.width, -scene.height, scene.width, scene.height);
        }
        else if (step === 3) {
            ctx2.rotate(270 * Math.PI / 180);
            ctx2.drawImage(origin, 0, 0, origin.width, origin.height, -scene.height, 0, scene.height, scene.width);
        }
        else if (step === 0) {
            ctx2.rotate(0 * Math.PI / 180);
            ctx2.drawImage(origin, 0, 0, origin.width, origin.height, 0, 0, scene.width, scene.height);
        }

        ctx2.restore(); //绘制结束以后,恢复画笔状态 

        document.getElementById(pid + 'Preview').src = scene.toDataURL();

    }
    </script>
    <!-- target: footer -->

</body>

</html>