Search code examples
javascriptc++canvasgraphicsduktape

DukTape Display JavaScript Canvas on GLUT Window


I managed to get DukTape working in my GLUT project (it is able to run inline javascript with duk_eval_string();). Is it possible to display a static html canvas with javascript graphics in a C++ GLUT window using DukTape?


Solution

  • Using the HTML5 canvas drawing methods is not possible in Duktape. Duktape is a Javascript engine, what means that it allows you to execute ES5/5.1 compliant code. Displaying a HTML canvas is a task Duktape can't do.

    If you ultimately want to achieve this, try searching for a library to achieve such a task, maybe look at the Firefox source. If you want to do it completely from scratch you would need to add C function bindings (Example at duktape.org/) for every draw method you want. An example would be like this:

    // C/C++ code:
    // C function to be used in the Javascript engine 
    int js_draw_rect(duk_context *ctx) {
        // get parameters from javascript function call
        int pos_x = duk_get_number(ctx, -4);
        int pos_y = duk_get_number(ctx, -3);
        ...
    
        // C/C++ code to draw the rectangle (in your case probably GLUT)
        draw_rectangle(pos_x, pos_y, ...);
        return 0;
    }
    
    int main(void) {
        duk_context *ctx;
        ...
    
        // this snippet adds a binding for the function 'js_draw_rect' so it can be called from Javascript code
        duk_push_global_object(ctx);
        duk_push_c_function(ctx, js_draw_rect, 4/*number of args the JS function has*/);
        duk_put_prop_string(ctx, -2 /*idx:global*/, "drawRect"/*name of function in JS environment*/);
        duk_pop(ctx);
    }
    
    // Javascript code:
    drawRect(50, 50, 100, 200);
    ...
    

    This method allows you to create C/C++ functions which handle all drawing and later bind them all to the Javascript engine so they can be called in JS.