【问题标题】:How can i draw a line with canvas to specific Coordinates in display... (absolute cordinate)我如何用画布画一条线到显示中的特定坐标...(绝对坐标)
【发布时间】:2022-01-11 03:24:01
【问题描述】:

我是画布和 svg 的新手。我想在特定坐标之间制作画布或 svg 线 例如,我有两个矩形,我必须在它们之间画一条线(在这种情况下,我必须使这条线成为两个矩形的中心)

我尝试过的: 像这样的 SVG 代码:

HTML:

<svg version="1.1" id="line_2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="15px" xml:space="preserve">
  <path class="path2" fill="#01a09e" stroke-width="5" stroke="#01a09e" d="M0 0 l890 0"/>
</svg>

CSS:

.path2 {
  stroke-dasharray: 1120;
/*   stroke-dashoffset: 800; */
  animation: draw1 5s linear alternate;
}

@keyframes draw1 {
  from {
    stroke-dashoffset: 1120;
  }
  to {
    stroke-dashoffset: 2240;
  }
}

【问题讨论】:

标签: javascript html css svg canvas


【解决方案1】:

您可以通过仅使用画布来实现此目的。我用quadraticCurveTo()画曲线,用rect()画矩形。

quadraticCurveTo() 需要一个起点,这就是我在画线之前使用moveTo() 的原因。

const canvas = document.querySelector("canvas"),
      ctx = canvas.getContext("2d");
   
// Draw rectangle one ("r" stands for rectangle)  
let r_x = 20,
    r_y = 20,
    r_width = 80,
    r_height = 30;
    
ctx.beginPath();
ctx.rect(r_x, r_y, r_width, r_height);    
    
// Draw curved line     
let start_x = r_x + r_width*2/3,
    start_y = r_y + r_height,
    point_one = { x: 30, y: 130 },
    point_two = { x: 120, y: 150 };
    
ctx.moveTo(start_x, start_y)
ctx.quadraticCurveTo(
  point_one.x,
  point_one.y,
  point_two.x,
  point_two.y
);

// Draw second rectangle
r_x = 80, r_y = 150;

ctx.rect(r_x, r_y, r_width, r_height);

ctx.stroke();
&lt;canvas width="300" height="200"&gt;&lt;/canvas&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2013-02-24
    相关资源
    最近更新 更多