context.textAlign 不起作用

context.textAlign isn't working

本文关键字:不起作用 textAlign context      更新时间:2023-09-26

我是初学者,脚本中的代码称为context.textAlign = "centre";没有"Sample Text"移动到由 css 制作的画布边框的中心,所以我做错了什么还是错过了什么等。

谢谢

<!doctype html>
<html>
<head>
  <title>html5 canvas text</title>
  <style>
    #testCanvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <h1> canvas text </h1>
  <canvas id="testCanvas" width="500" height="300">Your browser does not support the canvas element.</canvas>
  <script>
    window.onload = function() {
      var canvas = document.getElementById("testCanvas");
      var context = canvas.getContext("2d");
      var x = canvas.width / 2;
      var y = canvas.height / 2;
      context.textAlign = "centre";
      context.font = "Bold 60pt Arial";
      context.fillStyle = 'rgba(0,0,255,0.5)';
      context.fillText("Sample Text", x, y);
      context.strokeStyle = "green";
      context.lineWidth = 3;
      context.strokeText("Sample Text", x, y);
    }
  </script>
</body>
</html>

错误的拼写错误:它是"中心"而不是"中心"。

<!doctype html>
<html>
<head>
  <title>html5 canvas text</title>
  <style>
    #testCanvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <h1> canvas text </h1>
  <canvas id="testCanvas" width="500" height="300">Your browser does not support the canvas element.</canvas>
  <script>
    window.onload = function() {
      var canvas = document.getElementById("testCanvas");
      var context = canvas.getContext("2d");
      var x = canvas.width / 2;
      var y = canvas.height / 2;
      context.textAlign = "center";
      context.font = "Bold 60pt Arial";
      context.fillStyle = 'rgba(0,0,255,0.5)';
      context.fillText("Sample Text", x, y);
      context.strokeStyle = "green";
      context.lineWidth = 3;
      context.strokeText("Sample Text", x, y);
    }
  </script>
</body>
</html>

textAligncentre更改为center

<!doctype html>
<html>
<head>
  <title>html5 canvas text</title>
  <style>
    #testCanvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <h1> canvas text </h1>
  <canvas id="testCanvas" width="500" height="300">Your browser does not support the canvas element.</canvas>
  <script>
    window.onload = function() {
      var canvas = document.getElementById("testCanvas");
      var context = canvas.getContext("2d");
      var x = canvas.width / 2;
      var y = canvas.height / 2;
      context.textAlign = "center";
      context.font = "Bold 60pt Arial";
      context.fillStyle = 'rgba(0,0,255,0.5)';
      context.fillText("Sample Text", x, y);
      context.strokeStyle = "green";
      context.lineWidth = 3;
      context.strokeText("Sample Text", x, y);
    }
  </script>
</body>
</html>