【问题标题】:clearRect text canvas html5clearRect 文本画布 html5
【发布时间】:2013-07-31 14:42:16
【问题描述】:

我在

中添加了一个画布文本
    <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/

非常感谢。

【问题讨论】:

  • 您的代码不完整。 context 未定义。 word 根本没有使用。 wrapText 未定义...

标签: html canvas html5-canvas


【解决方案1】:

wrapText() 调用后,使用这个:

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

this fiddle

注意:

  • p0.x 是你的 x 坐标(左边界),
  • p0.y 是你的 y 坐标(下边界),
  • metrics.width &gt; maxWidth ? metrics.width : maxWidth 是你的宽度,按照函数本身计算,
  • - text.split(' ').length * lineHeight 是负高度,因为文本已相应对齐;它是在函数本身中计算的

【讨论】:

  • 不准确。清除文本的矩形比必要的宽。
  • 这取决于你想如何使用它——更宽或更窄的计算。将代码更改为 metrics.width &lt; maxWidth ? metrics.width : maxWidth 以查看其他选项。
  • 嗯,现在它工作得更好了,但它并没有完全擦除这个词。您可以在此处查看示例:michelepierri.it/examples/canvas.html 和此处的问题 michelepierri.it/examples/ax.png 谢谢
  • 抱歉,我的提供商阻止了您的页面。 StackOverflow 鼓励使用 jsFiddle 和代码复制/粘贴。但是,它正在为你工作,对吧?
  • 查看我的回答,我描述了正在发生的事情
猜你喜欢
  • 2011-12-25
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
相关资源
最近更新 更多