0

I have write some JavaScript and now I want to change the text variable via php input. How can I do this? I hope there is any option to make it easy but right now I don't know anything about it.

var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var maxWidth = 252;
var lineHeight = 15;
var x = (canvas.width - maxWidth) / 2;
var y = 100;
var text = 'duuuuzo teeeekstuuu ksda sasdjk asjdk asjkdablsd ab dsjhabdsalkdbs adsj asbld';

function print(context, text, x, y, maxWidth, lineHeight) {
  var words = text.split(' ');
  var line = '';

  words.forEach(function(word) {
    var testLine = line + word + ' ';
    var metrics = context.measureText(testLine);
    var testWidth = metrics.width;
    if (testWidth > maxWidth) {
      context.fillText(line, x, y);
      line = word + ' ';
      y += lineHeight;
    } else {
      line = testLine;
    }
  });
  context.fillText(line, x, y);
}

context.fillStyle = '#333';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#fff';
context.font = '13px Arial, sans-serif';

print(context, text, x, y, maxWidth, lineHeight);
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Generator</title>
</head>

<body>
  <canvas width="272" height="340"></canvas>
  <script src="js/index.js"></script>
</body>

</html>

Can someone help me with this?

vard
  • 4,057
  • 2
  • 26
  • 46
  • If you want to retrieve a value via PHP and provide it to javascript *after* the page has loaded you would need to use AJAX. Your question is both very vague and broad, so it's difficult to know exactly what you're trying to do and why. – Rory McCrossan Nov 30 '15 at 16:30
  • Hmmm lets say thats im trying to make this picture thats is right now but i want to have the optin to change the text on it from the website and no need to go all time to FTP and changing JS file ;) – Szymon Domagała Nov 30 '15 at 16:33

2 Answers2

0

A few ideas come to mind:

  1. Have PHP handle the .js extension, and generate an .js file to fill that value
  2. have PHP set the value of the global text variable in your HTML (that would become an PHP page)
  3. Grab the value via AJAX.
McKay
  • 12,334
  • 7
  • 53
  • 76
0

Maybe you can use data-attribute under your canvas

<div id="myCanvas" data-text="<?php echo $myValue; ?>">
 <canvas width="272" height="340"></canvas>
</div>

You can get it like that:

 var text = document.getElementById('myCanvas').dataset.text;

How to pass variables and data from PHP to JavaScript?

Community
  • 1
  • 1
David Auvray
  • 288
  • 1
  • 3
  • 20