科大讯飞手写识别

$(function() {
    // $.ajax({
    // url : ,
    // type : 'GET',
    // async:  true,
    // dataType: 'json',
    // timeout: 7000, 
    // data : {
    // tel : $('#tel').val(),
    // pass : $('#pass').val()
    // },
    // success : function(data) {
    //                 
    // }, 
    // error : function(error) {
    //                 
    // }   
    // }); 

    document.getElementById('init').addEventListener('click', function(e) {
        e.stopPropagation();
        init();
        initSpeaker();
    }, false);
    document.getElementById('repeat').addEventListener('click', function(e) {
        e.stopPropagation();
        startSpeaking();
    }, false);
    document.getElementById('next').addEventListener('click', function(e) {
        e.stopPropagation();
        next();
    }, false);

    
    var data = '三九天寒 地冻 立刻';
    var words = new Array();
    var word = '';
    var index = 0;
    words = data.split(' ');
    var num = words.length;
    var during = 8000;
    var is_pause = false;
    var is_mousedown = false;
    // var is_clean = false;
    var single_data = '';   // 单字轨迹
    var curr_write = 0;     // 词语当前写的位置,默认从头开始写
    var hand_words = new Array();   // 手写的文字
    var errors = new Array();       // 存放对比结果
    errors[0] = new Array();        // 存放正确结果
    errors[1] = new Array();        // 存放错误结果
    
    $('.tip .index').html(index + 1);
    $('.tip .total').html(num);

    for (var i = 0; i < DataLength(words[0]); i++) {
        drawGrid($('.sm-grid')[0], 'sm-grid' + (i + 1), '140', '#FFC301');
    }
    drawGrid($('.lg-grid')[0], 'can', '640', '#FFC301');

    // init();
    // initSpeaker();
    // alert('init!');

    //计算词语字数
    function DataLength(fData) {
        var intLength = 0;
        for (var i = 0; i < fData.length; i++) {
            if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255))
                intLength = intLength + 1;
            else
                intLength = intLength + 0.5;
        }
        return intLength;
    }

    //语音
    function init() {
        var params = {
            appID: '5821c047'
        };
        var data = JSON.stringify(params);
        uexXunfei.init(data);
    }

    function initSpeaker() {
        var params = {
            //voiceName;      //设置发音人,默认是"xiaoyan" String类型 可以不传
            //speed;          //设置语速,默认是"50" String类型 可以不传
            //volume;         //设置音量,默认是"80" String类型 可以不传
        };
        var data = JSON.stringify(params);
        uexXunfei.initSpeaker(data);
    }

    function startSpeaking() {
        word = words[index];
        var params = {
            text: word
        };
        var data = JSON.stringify(params);
        uexXunfei.startSpeaking(data);
    }

    function pause() {
        if (is_pause) {
            uexXunfei.resumeSpeaking();
            is_pause = false;
        } else {
            uexXunfei.pauseSpeaking();
            is_pause = true;
        }
    }

    function next(){
        var w = '';
        for(var i=0;i<$('.sm-grid .wrapper').length;i++){
            w += $('.sm-grid .wrapper:eq('+i+') .font').html();
        }
        hand_words[index] = w;
        console.log(hand_words[index]);
        
        index++;
        clearSingleData();
        single_data = '';
        if (index > num - 1) {
            // index--;  
            for(var i=0;i<$('.sm-grid .wrapper').length;i++){
                w += $('.sm-grid .wrapper:eq('+i+') .font').html('');
            }
            var j=0;         
            for(var i=0;i
'); // $err_tip.append('

你有'+j+'个错误!

'); // var $right = $('
'); // var $error = $('
'); // $err_tip.append($right); // $err_tip.append($error); // $right.append('正确'); // $error.append('错误'); // for(var i=0;i'+errors[0][i]+''); // $error.append(''+errors[1][i]+''); // } // $('.dictation').append($err_tip); // // $(document).click(function(){ // $err_tip.remove(); // $(document).unbind('click'); // }); return; } $('.tip .index').html(index + 1); $('.sm-grid').empty(); for (var i = 0; i < DataLength(words[index]); i++) { drawGrid($('.sm-grid')[0], 'sm-grid' + (i + 1), '140', '#FFC301'); } curr_write = 0; word = words[index]; var params = { text: word }; var data = JSON.stringify(params); uexXunfei.startSpeaking(data); } //米字格 function drawGrid($container, id, size, color) { var wrapper = document.createElement('DIV'); var oCanvas = document.createElement('CANVAS'); wrapper.className = 'wrapper'; oCanvas.id = id; oCanvas.width = size; oCanvas.height = size; $container.appendChild(wrapper); wrapper.appendChild(oCanvas); if (id == 'can') { var paint = document.createElement('CANVAS'); paint.id = 'paint'; paint.width = size; paint.height = size; wrapper.appendChild(paint); } else { var font = document.createElement('DIV'); font.className = 'font'; font.style.lineHeight = size + 'px'; font.style.width = size + 'px'; font.style.height = size + 'px'; wrapper.appendChild(font); } if (oCanvas.getContext) { var ctx = oCanvas.getContext('2d'), l = 0, w = oCanvas.width, half = w / 2, span = 5; //每条虚线的实线部分长度为5 // ctx.translate(left, top); // ctx.moveTo(0,0); ctx.strokeStyle = color; ctx.lineWidth = 3; ctx.strokeRect(1, 1, w - 2, w - 2); drawUnReal(ctx); //画虚线,兼容性没问题! function drawUnReal(ctx) { ctx.save(); ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(0, half); l = w / 5; //横线路径 for (var i = 0; i < l; i += 2) { ctx.lineTo(i * span, half); ctx.moveTo((i + 1) * span, half); } //竖线路径 ctx.moveTo(half, 0); for (var i = 0; i < l; i += 2) { ctx.lineTo(half, i * span); ctx.moveTo(half, (i + 1) * span); } ctx.translate(half, half); ctx.rotate(45 * Math.PI / 180); ctx.moveTo(0, -half * Math.SQRT2); l = Math.ceil(w * Math.SQRT2 / 5); // 交叉线1 for (var i = 0; i < l; i += 2) { ctx.lineTo(0, -half * Math.SQRT2 + i * span); ctx.moveTo(0, -half * Math.SQRT2 + (i + 1) * span); } ctx.rotate(90 * Math.PI / 180); // ctx.strokeRect(1, 1, w - 2, w - 2); ctx.moveTo(0, -half * Math.SQRT2); //交叉线2 for (var i = 0; i < l; i += 2) { ctx.lineTo(0, -half * Math.SQRT2 + i * span); ctx.moveTo(0, -half * Math.SQRT2 + (i + 1) * span); } //统一描边节省性能! ctx.stroke(); ctx.restore(); } } } // 手写功能 function write(e){ var oCanvas = document.getElementById('paint'); if (oCanvas.getContext) { var ctx = oCanvas.getContext('2d'); } var touch = e.targetTouches[0]; var x = touch.pageX - getAbsLeft(touch.target); var y = touch.pageY - getAbsTop(touch.target); // var x = e.pageX - getAbsLeft(e.target); // var y = e.pageY - getAbsTop(e.target); // alert('x:'+x+' y:'+y); single_data += x + ',' + y + ','; ctx.beginPath(); ctx.arc(x, y, 4, 0, 2 * Math.PI, false); ctx.fillStyle = '#000'; ctx.fill(); ctx.closePath(); } //手动清空手写板上的内容 // function clear(e) { // var oCanvas = document.getElementById('paint'); // if (oCanvas.getContext) { // var ctx = oCanvas.getContext('2d'); // } // // var touch = e.targetTouches[0]; // // var x = touch.pageX - getAbsLeft(touch.target); // // var y = touch.pageY - getAbsTop(touch.target); // // var x = e.pageX - getAbsLeft(e.target); // var y = e.pageY - getAbsTop(e.target); // // ctx.clearRect(x - 8, y - 8, x + 8, y + 8); // // ctx.beginPath(); // // ctx.arc(x,y,40,0,2*Math.PI,false); // // ctx.fillStyle = '#fff'; // // ctx.fill(); // // ctx.closePath(); // } //自动清空手写板上的内容 function clearSingleData(){ var oCanvas = document.getElementById('paint'); if (oCanvas.getContext) { var ctx = oCanvas.getContext('2d'); } ctx.clearRect(0, 0, oCanvas.width, oCanvas.height); } document.getElementById('write').addEventListener('click', function(e) { e.stopPropagation(); // if (!is_clean){ // is_clean = true; clearSingleData(); // e.target.innerHTML = '写字'; // }else{ // is_clean = false; // e.target.innerHTML = '清除'; // } }, false); //手机版 var can = document.getElementById('can'); can.addEventListener('touchstart', function(e) { // 如果这个元素的位置内只有一个手指的话 if (e.targetTouches.length == 1) { // alert('down'); var touch = e.targetTouches[0]; var x = touch.pageX - getAbsLeft(touch.target); var y = touch.pageY - getAbsTop(touch.target); single_data += x + ',' + y + ','; is_mousedown = true; } }, false); can.addEventListener('touchend', function(e) { // 一个手指离开屏幕,touches和targetTouches中对应的元素会同时移除,而changedTouches仍然会存在元素。 // alert('end'); single_data += '-1,0,'; is_mousedown = false; }, false); document.addEventListener('touchmove', function(e) { e.preventDefault(); // 在这个事件发生期间,调用preventDefault()可阻止滚动。 if (e.targetTouches.length > 1 || event.scale && event.scale !== 1) return; // 如果这个元素的位置内只有一个手指的话 if (e.targetTouches.length == 1) { // alert('move'); if (is_mousedown) { // if (!is_clean) { write(e); // } } } }, false); //测试版 // $('.lg-grid').on('mousedown','#can',function(e){ // // console.log('down'); // var x = e.pageX - getAbsLeft(e.target); // var y = e.pageY - getAbsTop(e.target); // // single_data += x+','+y+','; // is_mousedown = true; // }); // // mouseup只能绑定在document上并且on内不能具体选择到'#can' // $(document).on('mouseup','#can',function(e){ // // console.log(single_data); // console.log('up'); // single_data += '-1,0,'; // console.log(single_data); // is_mousedown = false; // }); // $('.lg-grid').on('mousemove','#can',function(e){ // // console.log('move'); // if(is_mousedown){ // if(!is_clean){ // console.log('write'); // write(e); // } // } // }); function getAbsLeft(obj) { var l = obj.offsetLeft; while (obj.offsetParent != null) { obj = obj.offsetParent; l += obj.offsetLeft; } return l; } function getAbsTop(obj) { var top = obj.offsetTop; while (obj.offsetParent != null) { obj = obj.offsetParent; top += obj.offsetTop; } return top; } // 调用汉王云接口识别单字 $('.sm-grid').on('click', '.wrapper', function() { // 用户未写字只是想要重新写 if (single_data == '') { curr_write = $('.sm-grid .wrapper').index($(this)); console.log('curr_write: ' + curr_write); return; } single_data += '-1,-1'; console.log(single_data); var passData = { 'uid': '192.168.155.1', 'type': '1', 'data': single_data }; $.ajax({ url: 'http://api.hanvon.com/rt/ws/v1/hand/single?key=d44e2db0-240a-4acb-abbf-8d1980d59374&&code=83b798e7-cd10-4ce3-bd56-7b9e66ace93d', type: 'POST', async: false, contentType: 'application/octet-stream', data: JSON.stringify(passData), success: function(data) { console.log(data); data = utf8to16(base64decode(data)); data = JSON.parse(data); if (data.code == 0) { var fonts = unicodeToString(data.result); $('.sm-grid .wrapper:eq(' + curr_write + ')').find('.font').html(fonts.charAt(0)); } }, error: function(error) { alert('出现位置错误!'); } }); clearSingleData(); // curr_write = $(this).index(); //这次点击的位置就是下次要写入的位置').index($(this)); curr_write = $('.sm-grid .wrapper').index($(this)); single_data = ''; console.log('curr_write: ' + curr_write); }); // base64解码,将结果解析成json串 // value = utf8to16(base64decode(src)); var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1); function base64decode(str) { var c1, c2, c3, c4; var i, len, out; len = str.length; i = 0; out = ""; while (i < len) { do { c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff]; } while (i < len && c1 == -1); if (c1 == -1) break; do { c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff]; } while (i < len && c2 == -1); if (c2 == -1) break; out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4)); do { c3 = str.charCodeAt(i++) & 0xff; if (c3 == 61) return out; c3 = base64DecodeChars[c3]; } while (i < len && c3 == -1); if (c3 == -1) break; out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2)); do { c4 = str.charCodeAt(i++) & 0xff; if (c4 == 61) return out; c4 = base64DecodeChars[c4]; } while (i < len && c4 == -1); if (c4 == -1) break; out += String.fromCharCode(((c3 & 0x03) << 6) | c4); } return out; } function utf8to16(str) { var out, i, len, c; var char2, char3; out = ""; len = str.length; i = 0; while (i < len) { c = str.charCodeAt(i++); switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += str.charAt(i - 1); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = str.charCodeAt(i++); char3 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out; } //unicode十进制串转为中文(unicode十进制转16进制,然后再转中文) function unicodeToString(str) { var array = null; console.log(str); str = str.substring(0, str.length - 1); array = str.split(','); for (var i = 0; i < array.length; i++) { array[i] = parseInt(array[i]).toString(16); //数字才有进制的概念 } str = array.join('\\u'); str = '\\u' + str; console.log(str); str = unescape(str.replace(/\\u/g, "%u")); console.log(str); return str; } });

你可能感兴趣的:(科大讯飞手写识别)