How do I duplicate a shape in HTML5's canvas?

canvas, html, html5-canvas, javascript

Solution

You could just move your shape into a function, call it once, and then use another state (`save`, `restore`) to add a mirror effect (using `transform` or `scale`+`translate`) and call it again:

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();

See MDN: Transformations for examples.

Problem

I have a semi-complex and horizontally symmetrical shape I am trying to build using HTML5. While I was trying to finish it I realized it would be easier if I could just duplicate half of the shape, mirror it and move it to join the two images together. I'm finding examples of how to mirror and move a shape, but not on how to duplicate it. Obviously, I'm hoping I won't need two separate canvas elements. Here is my code for reference: ``` 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(); ```

Original source