通过PHP更改JS值

Change JS value via PHP

本文关键字:JS 更改 PHP 通过      更新时间:2023-09-26

我已经写了一些JavaScript,现在我想通过php输入更改text变量。我该怎么做?我希望有任何选择可以让它变得简单,但现在我对此一无所知

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>

有人能帮我吗?

脑海中浮现出几个想法:

  1. 让PHP处理.js扩展名,并生成一个.js文件来填充该值
  2. 让PHP设置HTML中全局text变量的值(这将成为一个PHP页面)
  3. 通过AJAX获取值

也许您可以在画布下使用数据属性

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

你可以这样得到:

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

如何将变量和数据从PHP传递到JavaScript?