картинка с камеры, действующая как ссылка на камеру вместо пользовательского события клика - PullRequest
1 голос
/ 17 октября 2011

Я пишу веб-приложение для Android с PhoneGap + JQuery Mobile и я испытываю странную проблему - я получаю изображение, используя метод getPicture либо с base64 или image_uri, а затем переписать изображение (через Image ()) в элемент canvas с drawimage.

все работает - (оба способа извлечения картинки), но изображение, созданное на элементе canvas, становится своего рода ссылкой на камеру. поэтому, когда я щелкаю по картинке вместо того, чтобы инициировать событие click, привязанное к холсту, меня отправляют обратно в камеру, так что функция «flowercolor», которая должна срабатывать при щелчке, вообще не включается

почему это? что мне не хватает?

будет ли метод "captureimage" работать по-другому?

HTML соответствующий код:

        <script type = "text/javascript" src = "./js/modernizr.custom.31415.js"></script>

        <link rel = "stylesheet" type ="text/css" href ="./css/jquery.mobile-1.0rc1.min.css"/>
    </head>
    <body dir ="rtl">

        <div id = "camera">
            <button data-role = "button" type = "button" id = "photo" >option1</button><br/>
            <button data-role = "button" type = "button" id = "photobase" >option2</button><br/>

            <span id = "showpic" style = "display:none;">showpic</span><br/>
            <span id = "debug"></span>

        </div>
        <div id = "colorpicker">


            <div id = "flowerpic">
            </div></br/>


            <span  class = "aftercamera" id= "picked_color_selected" style= "display: none;">

            </span><br/>
            <span id = "sim"></span>
        </div>
        </div><!--end content -->

         <!--scripts downloaded at the the end of the page -->
        <script type = "text/javascript" src = "./js/jquery-1.6.4.min.js"></script>
        <script type = "text/javascript" src = "./js/jquery.mobile-1.0rc1.min.js"></script>
        <script type = "text/javascript" src = "./js/phonegap-1.1.0.js"></script>
        <script type = "text/javascript">

                    $(document).ready(function(){
                        document.addEventListener('deviceready',function(){
                                var script = document.createElement('script');
                                script.type = "text/javascript";
                                script.src = "./js/flora.js";
                                document.getElementsByTagName('body')[0].appendChild(script);
                        },true);
                    });
        </script>
    </body>
</html>

и это соответствующие js (включая функции для работы с различными форматами данных изображения - image_uri и данными base64):

function initcanvas (imageURI) {
    $('.aftercamera').css('display','block');
    img = new Image();
    img.crossOrigin = ''; // no credentials flag. Same as img.crossOrigin='anonymous'
    img.src = imageURI;
    //load image to canvas
    img.onload = function(){
        var c = document.getElementById('fromimage');
        var ctx = c.getContext('2d');
        var width = window.innerWidth;
        var ratio = img.width/(width*0.9);
        if (ratio>1){
            img.width = img.width / ratio;
            img.height = img.height/ratio;
        }
        c.width = img.width;
        c.height = img.height;
        ctx.drawImage (img,0,0);
    };

}
function camerasuccess (imageURI){

    //$('#debug').html(imageURI[0]);
    if (!imageURI[0]) {
        $('#debug').html("לא התקבלה התמונה - נסה שנית");
    } else {
        $('#showpic').css('display','block').html("we have an image");
        console.log(imageURI[0]);
        initcanvas(imageURI[0]);
    }

 }

function camerabasesuccess (imagebase){

    //$('#debug').html(imageURI[0]);
    if (!imagebase) {
        $('#debug').html("לא התקבלה התמונה - נסה שנית");
    } else {
        $('#showpic').css('display','block').html("we have an image");
        console.log(imagebase);
        var d = "data:image/jpeg;base64,"+imagebase;
        initcanvas(d);
    }



}

/*function camerasuccess(imageBASE) {

    $('#showpic').css('display','block').html("we have an image");
    //var imgsrc = "data:image/jpeg;base64,"+imageBASE[0];
    //$('#imageplace').html('<img src ="'+imgsrc+'"/>');
    var useimg = document.getElementById('useimage');
    //
    useimg.style.display = 'block';
    useimg.src = "data:image/jpeg;base64,"+imageBASE;

}*/

function camerafail(error) {
    $('#showpic').css('display','block').html("משהו לא עבד - נסה שוב"+error);
}


function camera(){
    $('#showpic').css('display','block').html("טוען תמונת פרח");
    var opt = {quality:50,destinationType:destinationType.FILE_URI,pictureSource:pictureSource.CAMERA};
    navigator.camera.getPicture(camerasuccess,camerafail,opt);

}

function camerabase(){
    $('#showpic').css('display','block').html("טוען ");
    var opt = {quality:20,pictureSource:pictureSource.CAMERA};
    navigator.camera.getPicture(camerabasesuccess,camerafail,opt);

}


    function flowercolor(event){

code code

    }

$(document).ready(function(){

    //area = getpos(); //initiating geolocation
    getpos();
    var can;
    if (Modernizr.canvas){
        can = document.createElement('canvas');
        can.id = "fromimage";

    } else {
        can = document.createElement('p');
        can.style.display = "block";
        can.textContent ="can't activate the camera, please choose flower color by hand";
        /*var noncan = new Image();
        noncan.src = '.pic/pallete.jpg';
        noncan.style.display = 'block';
        $('#flowerpic').append(noncan);*/ 
    }
    $('#flowerpic').append(can);


    destinationType = navigator.camera.DestinationType;
    pictureSource = navigator.camera.PictureSourceType;
    //encoding = navigator.camera.Encodingtype; not supported in android
    $('#photo').click(function(){camera();});
    $('#photobase').click(function(){camerabase();});
    $('#fromimage').click(function(){flowercolor(event); });

});

редактирование: Может ли эта проблема быть связана с тем, что элемент, с которым я связываю событие click, создается с помощью javascript и добавляется с помощью jquery? У меня немного модной памяти, есть проблема с элементами, созданными после $ (document) .ready, но я не совсем уверен - еще раз спасибо за помощь!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...