Search code examples
javascripthtmlcanvasjspsych

including raw HTML node to canvas element


I want to combine canvas-slider-response plugin and RDK plugin to create response trial where observers change the coherence of the motion field using the slider.

The RDK plugin creates a canvas element and append it to the DOM to draw dots on the canvas. Because I want the slider function, inside of the RDK plugin, I added HTML element:

var html = '<div id="jspsych-canvas-slider-response-wrapper" style="margin: 100px 0px;">';
html += '<div id="jspsych-canvas-slider-response-stimulus">' + '<canvas id="jspsych-canvas-stimulus" height="' + trial.canvas_size[0] + '" width="' + trial.canvas_size[1] + '"></canvas>' + '</div>';
html += '<div class="jspsych-canvas-slider-response-container" style="position:relative; margin: 0 auto 3em auto; width:';

And then add that html variable to the html element with this method:

display_element.innerHTML = html;

Naturally, this overwrites on the canvas, shows the HTML element, but now the dots are gone (canvas is overwritten?).

I am somewhat aware that rendering HTML into a canvas is severely limited for security reasons. So tried some emulations:

1- I can render html element using creating SVG images: Rendering HTML elements to <canvas>. But then I can't interact with the images using the methods such as display_element.querySelector('#jspsych-canvas-slider-response-next').addEventListener('click', function () {}

2- I can also insertAdjacentHTML but with this method, the canvas element appears after the RDK element shows up at the screen - not together. Add elements to the DOM given plain text HTML using only pure JavaScript (no jQuery).

3- I figured an HTML renderer in JsPsych could solve my problem here. So I tried including the RDK as a stimulus function to the canvas-slider-response, but I can't find a way to call the function within the RDK plugin object. This is what I was trying to achieve:

var slider_trial = {
    type: 'canvas-slider-response',
    stimulus: function(c) {
        **callRDKPlugin(c);** ////// Something here /////
    },
    labels: ['Exactly<br>the same','Totally<br>different'],
    canvas_size: [200, 500],
    prompt: '<p>How different would you say the colors of these two squares are?</p>',
    on_finish: function(data) {
        data.color1 = colors[0];
        data.color2 = colors[1];
    }
};

Am I missing an easy step?

This is the desired image:

This is the desired image


Solution

  • Shortening the canvas (height) and appending div node to the HTML,

        var div = document.createElement("div");
        div.innerHTML= html
        display_element.appendChild(div);
    

    solved my problem.