Опубликован: 19.03.2014 | Доступ: свободный | Студентов: 329 / 26 | Длительность: 11:36:00
Специальности: Программист
Практическая работа 7:

Доступ к ресурсам мобильного устройства с использованием Cordova-плагинов

< Лекция 9 || Практическая работа 7: 123 || Лекция 10 >

Наполнение Cordova - проекта средствами работы с камерой и акселерометром

  1. Запустите Visual Studio и откройте проект Resources, к которому подключили плагины. Убедитесь, что в окне решений проекта появилась новая папка Plugin, содержащая установленные плагины:

  2. Откройте файл "index.html" и замените его содержимое следующим текстом разметки, содержащим обращения к установленным плагинам:
    <!DOCTYPE html>
    <html>
      <head>
        <title>Acceleration Example</title>
    
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">
    
            // The watch id references the current `watchAcceleration`
            var watchID = null;
    
            // Wait for device API libraries to load
            //
            document.addEventListener("deviceready", onDeviceReady, false);
    
            // device APIs are available
            //
            function onDeviceReady() {
                startWatch();
            }
    
            // Start watching the acceleration
            //
            function startWatch() {
    
                // Update acceleration every 3 seconds
                var options = { frequency: 3000 };
    
                watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
            }
    
            // Stop watching the acceleration
            //
            function stopWatch() {
                if (watchID) {
                    navigator.accelerometer.clearWatch(watchID);
                    watchID = null;
                }
            }
    
            // onSuccess: Get a snapshot of the current acceleration
            //
            function onSuccess(acceleration) {
                var element = document.getElementById('accelerometer');
    
                element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
                                    'Acceleration Y: ' + acceleration.y + '<br />' +
                                    'Acceleration Z: ' + acceleration.z + '<br />' +
                                    'Timestamp: ' + acceleration.timestamp + '<br />';
            }
    
            // onError: Failed to get the acceleration
            //
            function onError() {
                alert('onError!');
            }
    
        </script>
        <script type="text/javascript" charset="utf-8">
    
            var pictureSource;   // picture source
            var destinationType; // sets the format of returned value
    
            // Wait for device API libraries to load
            //
            document.addEventListener("deviceready", onDeviceReady, false);
    
            // device APIs are available
            //
            function onDeviceReady() {
                pictureSource = navigator.camera.PictureSourceType;
                destinationType = navigator.camera.DestinationType;
            }
    
            // Called when a photo is successfully retrieved
            //
            function onPhotoDataSuccess(imageData) {
                // Uncomment to view the base64-encoded image data
                // console.log(imageData);
    
                // Get image handle
                //
                var smallImage = document.getElementById('smallImage');
    
                // Unhide image elements
                //
                smallImage.style.display = 'block';
    
                // Show the captured photo
                // The inline CSS rules are used to resize the image
                //
                smallImage.src = "data:image/jpeg;base64," + imageData;
            }
    
            // Called when a photo is successfully retrieved
            //
            function onPhotoURISuccess(imageURI) {
                // Uncomment to view the image file URI
                // console.log(imageURI);
    
                // Get image handle
                //
                var largeImage = document.getElementById('largeImage');
    
                // Unhide image elements
                //
                largeImage.style.display = 'block';
    
                // Show the captured photo
                // The inline CSS rules are used to resize the image
                //
                largeImage.src = imageURI;
            }
    
            // A button will call this function
            //
            function capturePhoto() {
                // Take picture using device camera and retrieve image as base64-encoded string
                navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                    quality: 50,
                    destinationType: destinationType.DATA_URL
                });
            }
    
            // A button will call this function
            //
            function capturePhotoEdit() {
                // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
                navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                    quality: 20, allowEdit: true,
                    destinationType: destinationType.DATA_URL
                });
            }
    
            // A button will call this function
            //
            function getPhoto(source) {
                // Retrieve image file location from specified source
                navigator.camera.getPicture(onPhotoURISuccess, onFail, {
                    quality: 50,
                    destinationType: destinationType.FILE_URI,
                    sourceType: source
                });
            }
    
            // Called if something bad happens.
            //
            function onFail(message) {
                alert('Failed because: ' + message);
            }
    
        </script>
      </head>
      <body>
        <div id="accelerometer">Waiting for accelerometer...</div>
            <button onclick="stopWatch();">Stop Watching</button>
        <button onclick="capturePhoto();">Capture Photo</button> <br>
        <button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
        <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
        <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
        <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
        <img style="display:none;" id="largeImage" src="" />
      </body>
    </html>

    Приведенный код взят из примеров, содержащихся в документации по Cordova: (http://cordova.apache.org/docs/en/3.1.0/index.html).

< Лекция 9 || Практическая работа 7: 123 || Лекция 10 >
Дмитрий Белов
Дмитрий Белов

Каким образом можно создать точку останова? Например, если в Лекции 8 в примере, который демонстрирует возможность <canvas> для работы с готовыми изображениями (последний в лекции) в цикле
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
sx = 300 * i; sy = 350 * j;
contextNow.drawImage(img, sx, sy);}
поставить точку останова, то при запуске отладки проекта точка становится пустой окружностью с сообщением: В настоящий момент попадание в точку останова не произойдет. Нет загруженных символов для этого документа. Как все-таки создать точку останова и пройти по шагам весь код?