Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Accessing Javascript variables in passages

edited December 2016 in Help! with 1.x
I'm trying to convert some of my images from CSS to Canvas, but am kinda stuck on how to access the canvas variables within passages.

The following code will create a full screen canvas image. However, I can't access the "sprite" variable in <<script>> tags (SugarCube) because they're not defined once you go away from the original passage that created the canvas. If I state this code in the Javascript passage, it will create the canvas image (with some small header.html div creation and css styling), but I can't then control it in game. To get control, I have to state the entire code every time, which I am guessing is bad.

It'd be nice if I could just go

<<script>>, 6, {alpha: 1});<</script>>

whenever I needed the image. Any way to do that? My intention is to use a permanent canvas to maintain a pool of background images so I don't need to constantly load them via the DOM.

var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, {
  view: document.querySelector("#canvas")

var texture = PIXI.Texture.fromImage("images/armoury3.webp");

var sprite = new PIXI.Sprite(texture);
sprite.alpha = 0;

var stage = new PIXI.Container();
var viewWidth = (renderer.width / renderer.resolution); 
stage.scale.x = 2560 / viewWidth;
stage.scale.y = stage.scale.x;

TweenLite.ticker.addEventListener("tick", function() {

function resize() {

    var canvas = document.getElementById('canvas');
    var canvasRatio = canvas.height / canvas.width;
    var windowRatio = window.innerHeight / window.innerWidth;
    var width;
    var height;

    if (windowRatio < canvasRatio) {
        height = window.innerHeight;
        width = height / canvasRatio;
    } else {
        width = window.innerWidth;
        height = width * canvasRatio;
    } = width + 'px'; = height + 'px';

window.addEventListener('resize', resize, false);
TweenMax.set(canvas, {zIndex: -5});, 6, {alpha: 1});


  • edited December 2016
    It's a scoping issue. The two easiest solutions would be to make sprite either a global or a property of SugarCube's setup object.

    SOLUTION 1: As a global
    window.sprite = new PIXI.Sprite(texture);
    Usage: (no change), 6, { alpha : 1 });

    SOLUTION 2: Via the setup object
    setup.sprite = new PIXI.Sprite(texture);
    Usage:, 6, { alpha : 1 });
  • edited December 2016
    Cheers! That makes using canvas much easier. I did the first because am lazy and it works as expected.
Sign In or Register to comment.