Introduction
Imagien you'd like to add JavaScript code components, but have some trouble understanding the PsychoJS API. This experiment shows how to expose PsychoJS objects to the web browser, so that you can access them via the browser console, and try things out in order to see what works (or not).
How does it work?
By default, PsychoJS variables are inside of modules, so you cannot access them from within the web page that contains your PsychoJS experiment runs inside of. By attaching variables to the window object, you can access them, and so manipulate them via the browser console.
The experiment contains three stimuli, a mouse, and a code component. In the "Begin Routine" tab, the code component exposes the following variables:
-
psychoJS
, which is an instance of the class PsychoJS - The static class
util
-
my_rectangle
, which is an instance of the class Polygon -
my_image
, which is an instance of the class ImageStim -
my_text
, which is an instance of the class TextStim -
my_mouse
, which is an instance of the class Mouse
Each of these is exposed by attaching them to the window object. For example: window.my_rectangle = myrectangle
Opening the browser console
- Open your web browser
- In your web browser, open Developer Tools. For Chrome and Firefox, this can be done by pressing the F12-key. For Safari, see this guide. For this tutorial, we'll use Chrome.
- Start your experiment. For this tutorial experiment, navigate to https://run.pavlovia.org/tpronk/tutorial_js_expose_psychojs.
- After the experiment loaded, click OK to start it.
- Click the "Console" tab in Developer Tools.
Basic examples
Once the console is open, you can try things out with the exposed PsychoJS objects and immediately see the results. Below are some examples, which you can run by copy-pasting the code into the console.
- Get the width and height of the canvas (in pixels).
psychoJS.window.size
- Shuffle an array.
util.shuffle([1,2,3])
- Change the color of the rectangle to red.
my_rectangle.fillColor = new util.Color([1, -1, -1], util.Color.COLOR_SPACE.RGB);
- Change the position of the image to the top.
my_image.setPos([0, 0.45]);
- Set the text of intro_text to "Hi there!".
my_text.setText('Hi there!');
- Get the mouse coordinates.
my_mouse.getPos()
More tutorials
This tutorial is part of a collection of small how-to guides; see this repo for the whole list.