0

我添加了一个画布文本

    <canvas id="canvasOne" width="500" height="500">
       Your browser does not support HTML5 Canvas.
    </canvas>

Javascript代码:

    theCanvas = document.getElementById("canvasOne");
    var context = theCanvas.getContext("2d");
    var text = 'word';

    context.font = '16pt Calibri';
    context.fillStyle = '#333';

    var p0 = {x:x0,y:y0};
    var word = {x:p0.x, y:p0.y, velocityx: 0, velocityy:0};

    var lastTime = new Date().getTime();

    wrapText(context, text, p0.x, p0.y, maxWidth, lineHeight);

wrapText 函数():

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

    for(var n = 0; n < words.length; n++) {
      var testLine = line + words[n] + ' ';
      var metrics = context.measureText(testLine);
      var testWidth = metrics.width;
      if (testWidth > maxWidth && n > 0) {
        context.fillText(line, x, y);
        line = words[n] + ' ';
        y += lineHeight;
      }
      else {
        line = testLine;
      }
    }
    context.fillText(line, x, y);
  }

如何使用 clearRect() 仅删除单词框?

      context.clearRect(word.x, word.y, word.x + offsetX, word.y + offsetY);

更新

部分解决了@Ozren Tkalčec Krznarić 技巧。但它并没有完全抹去这个词,部分先例没有抹去(见上图)。 在此处输入图像描述

您可以在这里看到问题:michelepierri.it/examples/canvas.html

jsfiddle:http: //jsfiddle.net/michelejs/yHnYh/6/

非常感谢。

4

1 回答 1

1

通话后wrapText(),使用这个:

context.clearRect(
  p0.x, 
  p0.y, 
  metrics.width > maxWidth ? metrics.width : maxWidth, 
  - text.split(' ').length * lineHeight);

看到这个小提琴

注意:

  • p0.x是您的 x 坐标(左边界),
  • p0.y是你的 y 坐标(下边界),
  • metrics.width > maxWidth ? metrics.width : maxWidth是你的宽度,在函数本身中计算,
  • - text.split(' ').length * lineHeight你是负高度,因为文本是相应对齐的;它是在函数本身中计算的
于 2013-07-31T08:14:49.987 回答