Холст. Выровнять текст - PullRequest
       6

Холст. Выровнять текст

0 голосов
/ 10 ноября 2019

Этот код удовлетворил бы меня, но для выравнивания текста. Верхняя и нижняя линии не выровнены по центру линий. Не могли бы вы помочь мне здесь?

function redrawMeme(image, topLine, bottomLine) {
  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext("2d");

  ctx.textAlign = "center";

  var height = Math.min(image.height, canvas.height);
  var width = Math.min(image.width, canvas.width);

  ctx.drawImage(image, 0, 0, width, height);

  var font = "bold 24px verdana, sans-serif ";
  ctx.font = font;

  var fillStyle = "white";
  ctx.fillStyle = fillStyle;

  var strokeStyle = "black";

  if (topLine) {
    ctx.fillText(topLine, 50, 50);
    ctx.strokeText(topLine, 50, 50);
  };

  if (bottomLine) {
    ctx.fillText(bottomLine, 50, 350);
    ctx.strokeText(bottomLine, 50, 350);
  };
}

// The following code is just for the example:
const img = new Image(500, 500);
img.src = 'https://api.adorable.io/avatars/500/abott@adorable.png';

img.onload = function() {
  redrawMeme(img, 'Top', 'Bottom');
}
<canvas id="canvas" width="500" height="500"></canvas>

1 Ответ

1 голос
/ 10 ноября 2019

Это потому, что текст холста выровнен по центру, поэтому левый и правый концы каждой строки зависят от длины текста. Вы можете выровнять их, установив их координаты х в центр ширины, например:

function redrawMeme(image, topLine, bottomLine) {
  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext("2d");

  ctx.textAlign = "center";

  var height = Math.min(image.height, canvas.height);
  var width = Math.min(image.width, canvas.width);

  ctx.drawImage(image, 0, 0, width, height);

  var font = "bold 24px verdana, sans-serif ";
  ctx.font = font;

  var fillStyle = "white";
  ctx.fillStyle = fillStyle;

  var strokeStyle = "black";

  var centerX = width / 2

  if (topLine) {
    ctx.fillText(topLine, centerX, 50);
    ctx.strokeText(topLine, centerX, 50);
  };

  if (bottomLine) {
    ctx.fillText(bottomLine, centerX, 350);
    ctx.strokeText(bottomLine, centerX, 350);
  };
}

// The following code is just for the example:
const img = new Image(500, 500);
img.src = 'https://api.adorable.io/avatars/500/abott@adorable.png';

img.onload = function() {
  redrawMeme(img, 'Top', 'Bottom');
}
<canvas id="canvas" width="500" height="500"></canvas>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...