如何在HTML5的画布中复制形状?

Jer*_*ith 3 javascript html5 canvas html5-canvas

我有一个半复杂和水平对称的形状,我试图使用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();
Run Code Online (Sandbox Code Playgroud)

Zet*_*eta 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();
Run Code Online (Sandbox Code Playgroud)

有关示例,请参阅MDN:转换.