javascript - 找到两点之间的中点

标签 javascript html canvas

我有一堆 HTML 元素,我想通过 Canvas 将它们与线条连接起来。这是我要实现的目标的模型:

Mockup

目前,我只有线条,没有文字。我想在每行中间放置文本,但由于它们是对 Angular 线,所以我不确定该怎么做。

当前代码:

// 'connectors' is an array of points corresponding to 
// the middle of each big blue buttons' x-value 

ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<connectors.length;i++){
    var wpoint = connectors[i];
    var pos1   = {w: wpoint, h: 0};
    var pos2   = {w: canvas.width / 2, h: canvas.height};
    ctx.beginPath();
    ctx.moveTo(pos1.w,pos1.h);
    ctx.lineTo(pos2.w,pos2.h);
    ctx.stroke();

    // Write Text Halfway 
    ctx.fillStyle = "blue";
    ctx.font = "bold 16px Arial";
    ctx.fillText("2702", 100, canvas.height / 2); 
    // No idea what to put as the x value here

}

实现此目标的最佳方法是什么?可能画一半线,写文本,然后画线的其余部分?

编辑:也许更好的标题/问题是:如何在 HTML Canvas 中找到两个任意点之间的中点?我想在那里画文字。

最佳答案

enter image description here

方法如下:

  • 计算直线的中点
  • 划清界线
  • 删除中点的线
  • 告诉 canvas 将任何绘制的文本围绕指定的 [x,y] 水平和垂直居中
  • 在中点绘制文字

这是带注释的代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var line={x0:20,y0:20,x1:150,y1:150};

textAtMidLine(line,'2702','verdana',14)

function textAtMidLine(line,text,fontface,fontsize){

  // save the unmodified context state
  ctx.save();

  // calc line's midpoint
  var midX=line.x0+(line.x1-line.x0)*0.50;
  var midY=line.y0+(line.y1-line.y0)*0.50;

  // calc width of text
  ctx.font=fontsize+'px '+fontface;
  var textwidth=ctx.measureText(text).width;

  // draw the line
  ctx.beginPath();
  ctx.moveTo(line.x0,line.y0);
  ctx.lineTo(line.x1,line.y1);
  ctx.lineWidth=2;
  ctx.strokeStyle='lightgray';
  ctx.stroke();

  // clear the line at the midpoint
  ctx.globalCompositeOperation='destination-out'; // "erases" 
  ctx.fillRect(midX-textwidth/2,midY-fontsize/2,textwidth,fontsize*1.286);
  ctx.globalCompositeOperation='source-over';  // reset to default

  // tell canvas to horizontally & vertically center text around an [x,y]
  ctx.textAlign='center';
  ctx.textBaseline='middle'

  // draw text at the midpoint
  ctx.fillText(text,midX,midY);

  // restore the unmodified context state
  ctx.restore();

}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

关于javascript - 找到两点之间的中点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34402883/

相关文章:

javascript - 在 Javascript 中从 JSON 获取多个无组织的值

php - 如何知道要在您的网站中更改哪些文件

javascript - 在窗口焦点事件之前,在 HTML 的 body 标记中运行 onload 事件

html - 如何将元素 (nav, h1) 标题模板 [http ://html5up.net/uploads/demos/alpha/][1] 置于中心?

javascript - Item 上的 Canvas 鼠标移动事件

javascript - 如何访问 Vue.js 中的动态元素?

javascript - 如何隐藏 HTML 源代码中的元素?

html - 如何删除选择框的背景

javascript - 在具有存储坐标的图像上绘制时考虑 Canvas 大小差异

javascript - 如何在 Canvas 上绘制适合给定矩形的文本?