HTML5画布带有圆角的三角形。

6

我是一名初学者,正在尝试使用HTML5 Canvas画一个带有圆角的三角形。

我已经尝试过:

ctx.lineJoin = "round";
ctx.lineWidth = 20;

但是它们都没有起作用。

这是我的代码:

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

ctx.scale(5, 5);
    
var x = 18 / 2;
var y = 0;
var triangleWidth = 18;
var triangleHeight = 8;

// how to round this triangle??
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + triangleWidth / 2, y + triangleHeight);
ctx.lineTo(x - triangleWidth / 2, y + triangleHeight);
ctx.closePath();
ctx.fillStyle = "#009688";
ctx.fill();
    
ctx.fillStyle = "#8BC34A";
ctx.fillRect(0, triangleHeight, 9, 126);
ctx.fillStyle = "#CDDC39";
ctx.fillRect(9, triangleHeight, 9, 126);
<canvas width="800" height="600"></canvas>

能否帮我一下?

3个回答

34

圆角处理

我经常使用的一个非常有用的功能是圆角多边形。它接收一组描述多边形顶点的二维点集,并添加弧以圆滑拐角。

圆角处理的问题在于,为了保持多边形区域的限制,您并不总能适合具有特定半径的圆角。

在这些情况下,您可以忽略拐角,将其保留为锐角,或者减小圆角半径以尽可能适应角落。

如果拐角过于锐利,且从拐角处出发的线段长度不足以获得所需半径,则以下函数将调整角落圆角半径以适应角落:

注意:代码中有关数学部分的注释,请参阅下面的数学部分。

roundedPoly(ctx, points, radius)

// ctx is the context to add the path to
// points is a array of points [{x :?, y: ?},...
// radius is the max rounding radius 
// this creates a closed polygon.
// To draw you must call between 
//    ctx.beginPath();
//    roundedPoly(ctx, points, radius);
//    ctx.stroke();
//    ctx.fill();
// as it only adds a path and does not render. 
function roundedPoly(ctx, points, radiusAll) {
  var i, x, y, len, p1, p2, p3, v1, v2, sinA, sinA90, radDirection, drawDirection, angle, halfAngle, cRadius, lenOut,radius;
  // convert 2 points into vector form, polar form, and normalised 
  var asVec = function(p, pp, v) {
    v.x = pp.x - p.x;
    v.y = pp.y - p.y;
    v.len = Math.sqrt(v.x * v.x + v.y * v.y);
    v.nx = v.x / v.len;
    v.ny = v.y / v.len;
    v.ang = Math.atan2(v.ny, v.nx);
  }
  radius = radiusAll;
  v1 = {};
  v2 = {};
  len = points.length;
  p1 = points[len - 1];
  // for each point
  for (i = 0; i < len; i++) {
    p2 = points[(i) % len];
    p3 = points[(i + 1) % len];
    //-----------------------------------------
    // Part 1
    asVec(p2, p1, v1);
    asVec(p2, p3, v2);
    sinA = v1.nx * v2.ny - v1.ny * v2.nx;
    sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;
    angle = Math.asin(sinA < -1 ? -1 : sinA > 1 ? 1 : sinA);
    //-----------------------------------------
    radDirection = 1;
    drawDirection = false;
    if (sinA90 < 0) {
      if (angle < 0) {
        angle = Math.PI + angle;
      } else {
        angle = Math.PI - angle;
        radDirection = -1;
        drawDirection = true;
      }
    } else {
      if (angle > 0) {
        radDirection = -1;
        drawDirection = true;
      }
    }
    if(p2.radius !== undefined){
        radius = p2.radius;
    }else{
        radius = radiusAll;
    }
    //-----------------------------------------
    // Part 2
    halfAngle = angle / 2;
    //-----------------------------------------

    //-----------------------------------------
    // Part 3
    lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));
    //-----------------------------------------

    //-----------------------------------------
    // Special part A
    if (lenOut > Math.min(v1.len / 2, v2.len / 2)) {
      lenOut = Math.min(v1.len / 2, v2.len / 2);
      cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
    } else {
      cRadius = radius;
    }
    //-----------------------------------------
    // Part 4
    x = p2.x + v2.nx * lenOut;
    y = p2.y + v2.ny * lenOut;
    //-----------------------------------------
    // Part 5
    x += -v2.ny * cRadius * radDirection;
    y += v2.nx * cRadius * radDirection;
    //-----------------------------------------
    // Part 6
    ctx.arc(x, y, cRadius, v1.ang + Math.PI / 2 * radDirection, v2.ang - Math.PI / 2 * radDirection, drawDirection);
    //-----------------------------------------
    p1 = p2;
    p2 = p3;
  }
  ctx.closePath();
}

您可以为每个点添加半径,例如{x :10,y:10,radius:20},这将设置该点的最大半径。半径为零将没有圆角。

数学计算

下图显示了两种可能性之一,适合的角度小于90度,另一种情况(大于90度)只有一些微小的计算差异(请参见代码)。 Shows circle in a corner

角落由红色的三个点ABC定义。圆形半径为r,我们需要找到绿色的点F,圆形中心和DE,它们将定义弧线的起始和结束角度。

首先,我们通过归一化两条线的向量并获取叉积来找到从B,AB,C的直线之间的角度。作为第1部分注释我们还找到BC与垂直于BA的90度线的夹角,因为这将有助于确定将圆放在线的哪一侧。

现在我们有了两条线之间的角度,我们知道这个角度的一半定义了圆的中心将坐在的线F,但是我们不知道该点距离B有多远。作为第2部分注释

有两个相同的直角三角形BDFBEF。我们已经知道B处的角度,而且我们知道DFEF两边的长度都等于圆的半径r,因此我们可以解决这个三角形,以获取从BF的距离。

为了方便,我将求解BD作为第3部分的注释,因为我将沿着该距离沿着线BC移动作为第4部分的注释,然后向上转90度并向上移动到F作为第5部分的注释。这一过程还给出了点D,并沿着线BA移动到E

我们使用点 D E 以及圆心 F (以抽象形式)来计算弧的起始角度和结束角度。在弧函数部分6中完成 其余代码涉及沿着线移动和离开的方向,以及扫描弧的方向。
代码部分 A 使用线 BA BC 的长度并将其与 BD 的距离进行比较。如果该距离大于一半的线长,我们知道该弧无法适配。然后我解决三角形问题,找到半径 DF ,如果线 BD BA BC 中最短线的一半长度。
示例用法。
片段是上述功能的简单示例。 单击以向画布添加点(需要至少3个点才能创建多边形)。 您可以拖动点并查看圆角如何适应尖角或短线。当片段运行时,会有更多信息。要重新启动,请重新运行片段。(有很多额外的代码可以忽略)
圆角半径设置为30。

const ctx = canvas.getContext("2d");
const mouse = {
  x: 0,
  y: 0,
  button: false,
  drag: false,
  dragStart: false,
  dragEnd: false,
  dragStartX: 0,
  dragStartY: 0
}

function mouseEvents(e) {
  mouse.x = e.pageX;
  mouse.y = e.pageY;
  const lb = mouse.button;
  mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
  if (lb !== mouse.button) {
    if (mouse.button) {
      mouse.drag = true;
      mouse.dragStart = true;
      mouse.dragStartX = mouse.x;
      mouse.dragStartY = mouse.y;
    } else {
      mouse.drag = false;
      mouse.dragEnd = true;
    }
  }
}
["down", "up", "move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));

const pointOnLine = {x:0,y:0};
function distFromLines(x,y,minDist){   
  var index = -1;
  const v1 = {};
  const v2 = {};
  const v3 = {};
  const point = P2(x,y);
  eachOf(polygon,(p,i)=>{
    const p1 = polygon[(i + 1) % polygon.length];
    v1.x = p1.x - p.x;
    v1.y = p1.y - p.y;
    v2.x = point.x - p.x;
    v2.y = point.y - p.y;
    const u = (v2.x * v1.x + v2.y * v1.y)/(v1.y * v1.y + v1.x * v1.x);
    if(u >= 0 && u <= 1){
      v3.x = p.x + v1.x * u;
      v3.y = p.y + v1.y * u;
      dist = Math.hypot(v3.y - point.y, v3.x - point.x);
      if(dist < minDist){
        minDist = dist;
        index = i;
        pointOnLine.x = v3.x;
        pointOnLine.y = v3.y;
      }
    }
  })
  return index;
  
}



function roundedPoly(ctx, points, radius) {
  var i, x, y, len, p1, p2, p3, v1, v2, sinA, sinA90, radDirection, drawDirection, angle, halfAngle, cRadius, lenOut;
  var asVec = function(p, pp, v) {
    v.x = pp.x - p.x;
    v.y = pp.y - p.y;
    v.len = Math.sqrt(v.x * v.x + v.y * v.y);
    v.nx = v.x / v.len;
    v.ny = v.y / v.len;
    v.ang = Math.atan2(v.ny, v.nx);
  }
  v1 = {};
  v2 = {};
  len = points.length;
  p1 = points[len - 1];
  for (i = 0; i < len; i++) {
    p2 = points[(i) % len];
    p3 = points[(i + 1) % len];
    asVec(p2, p1, v1);
    asVec(p2, p3, v2);
    sinA = v1.nx * v2.ny - v1.ny * v2.nx;
    sinA90 = v1.nx * v2.nx - v1.ny * -v2.ny;
    angle = Math.asin(sinA); // warning you should guard by clampling
                             // to -1 to 1. See function roundedPoly in answer or 
                             // Math.asin(Math.max(-1, Math.min(1, sinA)))
    radDirection = 1;
    drawDirection = false;
    if (sinA90 < 0) {
      if (angle < 0) {
        angle = Math.PI + angle;
      } else {
        angle = Math.PI - angle;
        radDirection = -1;
        drawDirection = true;
      }
    } else {
      if (angle > 0) {
        radDirection = -1;
        drawDirection = true;
      }
    }
    halfAngle = angle / 2;
    lenOut = Math.abs(Math.cos(halfAngle) * radius / Math.sin(halfAngle));
    if (lenOut > Math.min(v1.len / 2, v2.len / 2)) {
      lenOut = Math.min(v1.len / 2, v2.len / 2);
      cRadius = Math.abs(lenOut * Math.sin(halfAngle) / Math.cos(halfAngle));
    } else {
      cRadius = radius;
    }
    x = p2.x + v2.nx * lenOut;
    y = p2.y + v2.ny * lenOut;
    x += -v2.ny * cRadius * radDirection;
    y += v2.nx * cRadius * radDirection;
    ctx.arc(x, y, cRadius, v1.ang + Math.PI / 2 * radDirection, v2.ang - Math.PI / 2 * radDirection, drawDirection);
    p1 = p2;
    p2 = p3;
  }
  ctx.closePath();
}
const eachOf = (array, callback) => { var i = 0; while (i < array.length && callback(array[i], i++) !== true); };
const P2 = (x = 0, y = 0) => ({x, y});
const polygon = [];

function findClosestPointIndex(x, y, minDist) {
  var index = -1;
  eachOf(polygon, (p, i) => {
    const dist = Math.hypot(x - p.x, y - p.y);
    if (dist < minDist) {
      minDist = dist;
      index = i;
    }
  });
  return index;
}


// short cut vars 
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center 
var ch = h / 2;
var dragPoint;
var globalTime;
var closestIndex = -1;
var closestLineIndex = -1;
var cursor = "default";
const lineDist = 10;
const pointDist = 20;
var toolTip = "";
// main update function
function update(timer) {
  globalTime = timer;
  cursor = "crosshair";
  toolTip = "";
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
  ctx.globalAlpha = 1; // reset alpha
  if (w !== innerWidth - 4 || h !== innerHeight - 4) {
    cw = (w = canvas.width = innerWidth - 4) / 2;
    ch = (h = canvas.height = innerHeight - 4) / 2;
  } else {
    ctx.clearRect(0, 0, w, h);
  }
  if (mouse.drag) {
    if (mouse.dragStart) {
      mouse.dragStart = false;
      closestIndex = findClosestPointIndex(mouse.x,mouse.y, pointDist);
      if(closestIndex === -1){        
        closestLineIndex = distFromLines(mouse.x,mouse.y,lineDist);
        if(closestLineIndex === -1){
          polygon.push(dragPoint = P2(mouse.x, mouse.y));
        }else{
          polygon.splice(closestLineIndex+1,0,dragPoint = P2(mouse.x, mouse.y));
        }
        
      }else{
        dragPoint = polygon[closestIndex];
      }
    }
    dragPoint.x = mouse.x;
    dragPoint.y = mouse.y
    cursor = "none";
  }else{
    closestIndex = findClosestPointIndex(mouse.x,mouse.y, pointDist);
    if(closestIndex === -1){
      closestLineIndex = distFromLines(mouse.x,mouse.y,lineDist);
      if(closestLineIndex > -1){
        toolTip = "Click to cut line and/or drag to move.";
      }
    }else{
      toolTip = "Click drag to move point.";
      closestLineIndex = -1;
    }
  }
  ctx.lineWidth = 4;
  ctx.fillStyle = "#09F";
  ctx.strokeStyle = "#000";
  ctx.beginPath();
  roundedPoly(ctx, polygon, 30);
  ctx.stroke();
  ctx.fill();
  ctx.beginPath();
  ctx.strokeStyle = "red";
  ctx.lineWidth = 0.5;
  eachOf(polygon, p => ctx.lineTo(p.x,p.y) );
  ctx.closePath();
  ctx.stroke();
  ctx.strokeStyle = "orange";
  ctx.lineWidth = 1;
  eachOf(polygon, p => ctx.strokeRect(p.x-2,p.y-2,4,4) );
  if(closestIndex > -1){
     ctx.strokeStyle = "red";
     ctx.lineWidth = 4;
     dragPoint = polygon[closestIndex];
     ctx.strokeRect(dragPoint.x-4,dragPoint.y-4,8,8);
     cursor = "move";
  }else if(closestLineIndex > -1){
     ctx.strokeStyle = "red";
     ctx.lineWidth = 4;
     var p = polygon[closestLineIndex];
     var p1 = polygon[(closestLineIndex + 1) % polygon.length];
     ctx.beginPath();
     ctx.lineTo(p.x,p.y);
     ctx.lineTo(p1.x,p1.y);
     ctx.stroke();
     ctx.strokeRect(pointOnLine.x-4,pointOnLine.y-4,8,8);
     cursor = "pointer";     
  
  
  }

  if(toolTip === "" && polygon.length < 3){
    toolTip = "Click to add a corners of a polygon.";
  }
  canvas.title = toolTip;
  canvas.style.cursor = cursor;
  requestAnimationFrame(update);
}
requestAnimationFrame(update);
canvas {
  border: 2px solid black;
  position: absolute;
  top: 0px;
  left: 0px;
}
<canvas id="canvas"></canvas>


谢谢!提醒一下,由于浮点精度问题,在第一部分中sinA可能会被赋值为超过或低于1的值(1.00000000000000021 + Number.EPSILON)。这将导致角度变为NaN,因为Math.asin仅适用于介于-1和1之间的数字。为了解决这个问题,我只需将sinA变量夹在-1和1之间即可。 - the just shaping of letters
1
@thejustshapingofletters 列出的函数 roundedPoly 采用三元运算符 as < -1 ? -1 : a > 1 ? 1 : as 作为守卫,这在当时是最快的。最近使用 min 和 max 来夹紧更快,因此该行代码将变为 angle = Math.asin(Math.max(-1, Math.min(1, sinA)));。很抱歉,示例片段主要是概念证明(对于读者)和我的逻辑自检,不打算成为复制的解决方案。尽管我会添加一个警告,即 asinacos 应始终带有夹紧 -1、1 的守卫。 - Blindman67

7

我最初使用了@Blindman67的答案,对于基本静态形状来说效果还不错。

但是当我使用弧线法时遇到了一个问题,连续两个点在一起时与单独一个点非常不同。即使你的眼睛期望得到圆角,当有两个相邻的点时它也不会被圆滑。如果你正在动画化多边形的顶点,这个问题就会更加明显。

我通过使用贝塞尔曲线来解决这个问题。在我看来,这种方法在概念上更加简洁。我只需要使用二次曲线来创建每个角落,其中控制点是原始角落的位置。这样,即使有两个点在同一个位置,也几乎与只有一个点相同。

我还没有比较过性能,但似乎canvas在绘制贝塞尔曲线方面表现得很好。

和@Blindman67的答案一样,这并没有真正地绘制任何东西,所以在调用ctx.beginPath()之前和ctx.stroke()之后你需要进行调用。

/**
 * Draws a polygon with rounded corners 
 * @param {CanvasRenderingContext2D} ctx The canvas context
 * @param {Array} points A list of `{x, y}` points
 * @radius {number} how much to round the corners
 */
function myRoundPolly(ctx, points, radius) {
    const distance = (p1, p2) => Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)

    const lerp = (a, b, x) => a + (b - a) * x

    const lerp2D = (p1, p2, t) => ({
        x: lerp(p1.x, p2.x, t),
        y: lerp(p1.y, p2.y, t)
    })

    const numPoints = points.length

    let corners = []
    for (let i = 0; i < numPoints; i++) {
        let lastPoint = points[i]
        let thisPoint = points[(i + 1) % numPoints]
        let nextPoint = points[(i + 2) % numPoints]

        let lastEdgeLength = distance(lastPoint, thisPoint)
        let lastOffsetDistance = Math.min(lastEdgeLength / 2, radius)
        let start = lerp2D(
            thisPoint,
            lastPoint,
            lastOffsetDistance / lastEdgeLength
        )

        let nextEdgeLength = distance(nextPoint, thisPoint)
        let nextOffsetDistance = Math.min(nextEdgeLength / 2, radius)
        let end = lerp2D(
            thisPoint,
            nextPoint,
            nextOffsetDistance / nextEdgeLength
        )

        corners.push([start, thisPoint, end])
    }

    ctx.moveTo(corners[0][0].x, corners[0][0].y)
    for (let [start, ctrl, end] of corners) {
        ctx.lineTo(start.x, start.y)
        ctx.quadraticCurveTo(ctrl.x, ctrl.y, end.x, end.y)
    }

    ctx.closePath()
}


1
请问您能否添加一张关于您提到的问题和解决方案的截图? - root

2

ctx.lineJoin="round"这样的连接线样式适用于路径的描边操作 - 当考虑到它们的宽度、颜色、图案、虚线和类似的线条样式属性时。

线条样式适用于填充路径的内部。

因此,要影响线条样式,需要进行stroke操作。在下面的代码中,我将canvas输出翻译为不剪裁的结果,并描绘了三角形的路径,但没有描绘它下面的矩形:

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

ctx.scale(5, 5);
ctx.translate( 18, 12);
    
var x = 18 / 2;
var y = 0;
var triangleWidth = 48;
var triangleHeight = 8;

// how to round this triangle??

ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + triangleWidth / 2, y + triangleHeight);
ctx.lineTo(x - triangleWidth / 2, y + triangleHeight);
ctx.closePath();
ctx.fillStyle = "#009688";
ctx.fill();

// stroke the triangle path.

ctx.lineWidth = 3;
ctx.lineJoin = "round";
ctx.strokeStyle = "orange";
ctx.stroke();
    
ctx.fillStyle = "#8BC34A";
ctx.fillRect(0, triangleHeight, 9, 126);
ctx.fillStyle = "#CDDC39";
ctx.fillRect(9, triangleHeight, 9, 126);
<canvas width="800" height="600"></canvas>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接