Leo Frost Leo Frost - 5 months ago 19
Javascript Question

How to push variable change to active canvas draw

I am attempting to change a variable of a js array that draws onto canvas when a specific php session variable is set. The php is being ran in a separate div from the canvas element and js. The canvas and js are being ran from the main page and the php event occurs in a child element. I am currently using php to define the variable used in js and when a session is set I want it to update the variable to be displayed in the canvas.

Here is code from the parent page

<?php $colorin = 'rgba(81, 180, 200, 0.5)'; ?>


<script>

'use strict';



var rn = function rn(min, max) {
return Math.random() * (max - min) + min;
};
var ctx = iso.getContext('2d');

var _window = window;
var w = _window.innerWidth;
var h = _window.innerHeight;

var t = 10;
var arr = [];
var cn = 200;
var rad = 300;
var sp = rn(1, 5) / 10000;

iso.width = w;
iso.height = h;

while (~ ~ cn--) {
var angle = rn(110, 359);

arr = [].concat(arr, [{
color: '<?php echo $colorin ?>',
distortion: rn(15, 75),
tmod: rn(5, 10),
size: rn(15, 20),
speed: 0.0005,
angle: angle,
lastPos: {
x: w / 2,
y: h / 2
}
}]);
}

var draw = function draw() {
request = requestAnimationFrame(function () {
return draw();
});
t++;

ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0, 0, 0,.1)';
ctx.fillRect(0, 0, w, h);

var crad = rad * Math.sin(300);

ctx.globalCompositeOperation = 'lighter';
arr.forEach(function (el) {
ctx.strokeStyle = el.color;
ctx.lineWidth = el.size;
ctx.beginPath();

var lastPos = el.angle - el.speed;
var x = w / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.cos(el.angle * 180 / Math.PI);
var y = h / 2 + (crad + el.distortion * Math.sin(t / el.tmod)) * Math.sin(el.angle * 180 / Math.PI);

ctx.moveTo(el.lastPos.x, el.lastPos.y);
ctx.lineTo(x, y);

el.lastPos = { x: x, y: y };
el.angle = (el.angle + 0.0005) % 359;
ctx.stroke();
});
};

var resize = function resize() {
iso.width = w = window.innerWidth;
iso.height = h = window.innerHeight;
};

var request = requestAnimationFrame(function () {
return draw();
});
window.addEventListener('resize', function () {
return resize();
});

</script>


and here is the code from the page loaded into a div on the main page.

<?php
session_start();

if (isset($_SESSION['userid'])){
$userid = $_SESSION['userid'];
$colorin = 'rgba(81, 180, 200, 0.5)';

echo "
<script>
$(\"#loghold\").hide();
</script>
";
}else{

$colorin = 'rgba(255, 255, 255, 0.5)';



};

echo " ";



?>


I am unsure how to execute an update of the code since the div is updating but the parent page is obviously not. I want to update the running js without refreshing or reloading the whole page.

(when the main page is reloaded it does show the desired change)

bds bds
Answer

First of all, PHP is a server-side language, while JavaScript runs in the client's browser. The idea is, PHP can serve parts or whole HTML/CSS/JS parts of your page.

So, having that in mind. As far as I understood, you would like to change a DOM element without re-creating the DOM itself. Which means you have 2 options:

1) Either you use AJAX on the client-side to fetch a PHP script served by your Web-Server. PHP script should reply to the AJAX request with a JSON formatted string of Data that you consequently handle in your success call-back of the AJAX request.

2) Or you can use WebSockets. A decent explanation example is here.

There probably are other solutions, but these ones are least work-intensive in my opinion. Hope this helps!

UPDATE:

So here's what I have for you:

Two files in the web directory - one.php and two.php .

one.php:

// Your code from the first block here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        function checkStuff() {
            $.ajax({
                url:'/two.php',
                type: "POST",
                contentType: "application/json",
                dataType: "json",
                data: "{}",
                success: function(data) {
                    //debugger;
                    var colorin = data.color;
                    // apply colorin
                    var anything = data.anything;
                    // do whatever you want with anything
                },
                error: function(data) {
                    //debugger;
                }
            });
            setTimeout(checkStuff, 3000);
        }
        setTimeout(checkStuff, 3000);
    });
</script>

two.php:

<?php
session_start();
if (isset($_SESSION['userid'])){
    $userid = $_SESSION['userid'];
    echo $colorin = json_encode([
        'color' => 'rgba(81, 180, 200, 0.5)',
        'anything' => 'helloworld'
    ]);
} else {
    echo $colorin = json_encode([
        'color' => 'rgba(255, 255, 255, 0.5)',
        'anything' => 'anythingYouWant'
    ]);
}

So in one.php we produce our JS in which we have an AJAX function being executed every 3 seconds and depending on the response, we can do something with the color. Obviously feel free to adapt :)