3

我有一个半复杂的水平对称形状,我正在尝试使用 HTML5 构建。当我试图完成它时,我意识到如果我可以复制一半的形状,镜像并移动它以将两个图像连接在一起会更容易。我正在寻找如何镜像和移动形状的示例,而不是如何复制它。

显然,我希望我不需要两个单独的画布元素。

这是我的参考代码:

var canvas = document.getElementById(id),
      context = canvas.getContext("2d"),
      color,
      height = 50;
      width = 564;
      arrowWidth = 40,
      arrowHeight = 15,
      arrowStart = height - arrowHeight,
      edgeCurveWidth = 50;

    if (parseInt(id.substr(-1), 10) % 2) {
      color = "#F7E5A5";
    } else {
      color = "#FFF";
    }

    context.beginPath();
    context.lineWidth = 4;
    context.strokeStyle = "#BAAA72";
    context.moveTo(0, 0);
    context.quadraticCurveTo(-10, arrowStart, edgeCurveWidth, arrowStart);
    context.quadraticCurveTo(width/2 - arrowWidth/2 - 15, arrowStart - 15, width/2 - arrowWidth/2, arrowStart);
    context.quadraticCurveTo(width/2, height, width/2, height);
    context.stroke();
    context.lineTo(width/2, 0);
    context.closePath();
    context.fillStyle = color;
    context.fill();
4

1 回答 1

5

您可以将您的形状移动到一个函数中,调用一次,然后使用另一个状态 ( save, restore) 添加镜像效果(使用transformscale+ translate)并再次调用它:

function drawHalfShape(context,width, height,arrowWidth,arrowHeight,edgeCurveWidth,color){
    context.beginPath();
    context.lineWidth = 4;
    context.strokeStyle = "#BAAA72";
    context.moveTo(0, 0);
    context.quadraticCurveTo(-10, arrowStart, edgeCurveWidth, arrowStart);
    context.quadraticCurveTo(width/2 - arrowWidth/2 - 15, arrowStart - 15, width/2 - arrowWidth/2, arrowStart);
    context.quadraticCurveTo(width/2, height, width/2, height);
    context.stroke();
    context.lineTo(width/2, 0);
    context.closePath();
    context.fillStyle = color;
    context.fill();
}

var canvas = document.getElementById(id),
      context = canvas.getContext("2d"),
      color,
      height = 50;
      width = 564;
      arrowWidth = 40,
      arrowHeight = 15,
      arrowStart = height - arrowHeight,
      edgeCurveWidth = 50;

    if (parseInt(id.substr(-1), 10) % 2) {
      color = "#F7E5A5";
    } else {
      color = "#FFF";
    }

drawHalfShape(context,width,height,arrowWidth,arrowHeight,edgeCurveWidth,color);

context.save();
context.translate(-width/2,0); // these operations aren't commutative
context.scale(-1,0);           // these values could be wrong
drawHalfShape(context,width,height,arrowWidth,arrowHeight,edgeCurveWidth,color);
context.restore();

有关示例,请参见MDN:转换

于 2012-06-02T14:35:29.297 回答