Как создать экземпляр объекта JavaScript в C# Xamarin для WebView

Я пытаюсь использовать winwheel.js, это колесо фортуны, подобное призовому колесу, которое я хочу создать и использовать в Xamarin Android и отобразить в WebView.

Вот объектный код из html

var theWheel = new Winwheel({
            "outerRadius"     : 180,        // Set outer radius so wheel fits inside the background.
            "innerRadius"     : 5,         // Make wheel hollow so segments don"t go all way to center.
            "textFontSize"    : 24,         // Set default font size for the segments.
            "textOrientation" : "vertical", // Make text vertial so goes down from the outside of wheel.
            "textAlignment"   : "outer", 
            "centerX"         : 175,
            "centerY"         : 185,                // Align text to outside of wheel.
            "numSegments"     : 2,         // Specify number of segments.
            "segments"        :             // Define segments including colour and text.
            [                               // font size and test colour overridden on backrupt segments.
               {
            "fillStyle" : "#eae56f",
            "text"      : "Data 1 (45%)",
            "size"      : 180,   // Note use of winwheelPercentToDegrees()
            "moreInfo"  : "<p>Data 1 is the biggest slice of the pie at 45% for this year!</p>"
        },
        {
            "fillStyle" : "#89f26e",
            "text"      : "Data 2 (20%)",
            "size"      : 180,
            "moreInfo"  : "<p>Data 2 is selling well making up 20% of our sales.</p>"
        }                ],
            "animation" :           // Specify the animation to use.
            {
                "type"     : "spinToStop",
                "duration" : 8,     // Duration in seconds.
                "spins"    : 3,     // Default number of complete spins.
                "callbackFinished" : alertPrize
            }
        });

Вот функция, которую я могу вызвать, чтобы колесо вращалось

function startSpin(stopAngle)
        {
            // Ensure that spinning can"t be clicked again while already running.
            if (wheelSpinning == false)
            {
                // Based on the power level selected adjust the number of spins for the wheel, the more times is has
                // to rotate with the duration of the animation the quicker the wheel spins.
                if (wheelPower == 1)
                {
                    theWheel.animation.spins = 3;
                }
                else if (wheelPower == 2)
                {
                    theWheel.animation.spins = 6;
                }
                else if (wheelPower == 3)
                {
                    theWheel.animation.spins = 9;
                }


                // Begin the spin animation by calling startAnimation on the wheel object.
                // Begin the spin animation by calling startAnimation on the wheel object.
                //TheWheel.animation.stopAngle = 97;
                //var stopAt = (91 + Math.floor((Math.random() * 43)))

                theWheel.animation.stopAngle = stopAngle;                                        
                theWheel.startAnimation();

                // Set to true so that power can"t be changed and spin button re-enabled during
                // the current animation. The user will have to reset before spinning again.
                wheelSpinning = true;
            }
        }

Мне нужно настроить параметры колеса, изменив количество призовых сегментов, а также изменить цвета и текст.

Вот как я настроил веб-просмотр

webView = (WebView)FindViewById(Resource.Id.webView1);
        webView.Visibility = ViewStates.Invisible;

        webView.Settings.JavaScriptEnabled = true;

        webView.ClearCache(true);
        webView.LoadUrl(secret);

Вот как я могу крутить колесо

webView.EvaluateJavascript(string.Format("startSpin({0})", 92), new 
JavascriptResult());

Чего я не понимаю, так это того, как я изначально создаю экземпляр колеса, чтобы внести необходимые изменения.

Пожалуйста, помогите отметка

Эй, ты решил проблему?

Lucas Zhang - MSFT 03.01.2019 01:52

Да, см. Комментарий под вашим ответом, еще раз спасибо. Я правильно отметил ваш ответ :)

Mark 03.01.2019 16:54
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
2
120
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вы можете установить параметры в конструкторе и передать значение в ваше приложение.

function CreateWheel(outerRadius,innerRadius,textFontSize...)
{
  var theWheel = new Winwheel({
        "outerRadius"     : outerRadius,        // Set outer radius so wheel fits inside the background.
        "innerRadius"     : innerRadius,         // Make wheel hollow so segments don"t go all way to center.
        "textFontSize"    : textFontSize,         // Set default font size for the segments.
        "textOrientation" : "vertical", // Make text vertial so goes down from the outside of wheel.
        "textAlignment"   : "outer", 
        "centerX"         : 175,
        "centerY"         : 185,                // Align text to outside of wheel.
        "numSegments"     : 2,         // Specify number of segments.
        "segments"        :             // Define segments including colour and text.
        [                               // font size and test colour overridden on backrupt segments.
           {
        "fillStyle" : "#eae56f",
        "text"      : "Data 1 (45%)",
        "size"      : 180,   // Note use of winwheelPercentToDegrees()
        "moreInfo"  : "<p>Data 1 is the biggest slice of the pie at 45% for this year!</p>"
    },
    {
        "fillStyle" : "#89f26e",
        "text"      : "Data 2 (20%)",
        "size"      : 180,
        "moreInfo"  : "<p>Data 2 is selling well making up 20% of our sales.</p>"
    }                ],
        "animation" :           // Specify the animation to use.
        {
            "type"     : "spinToStop",
            "duration" : 8,     // Duration in seconds.
            "spins"    : 3,     // Default number of complete spins.
            "callbackFinished" : alertPrize
        }
    });
}

И в вашем проекте

webView.EvaluateJavascript("CreateWheel(150,5,24)",new JavascriptResult());

Спасибо, Лукас, правильным ответом является включение кода создания экземпляра в функцию. Однако мне потребовалось время, чтобы понять, что вам нужно объявить объект колеса вне функции, иначе он выпадает из области видимости. Итак, объявите глобал вне функции ..... var theWheel = null ..... и он работает

Mark 03.01.2019 16:52

Другие вопросы по теме