3

HTML5 を使用して構築しようとしている半複雑で水平対称の形状があります。完成させようとしているときに、シェイプの半分を複製し、ミラーリングし、移動して 2 つのイメージを結合できれば簡単であることに気付きました。形状をミラーリングして移動する方法の例を見つけていますが、複製する方法については見つけていません。

明らかに、2 つの別々のキャンバス要素が必要ないことを望んでいます。

参照用の私のコードは次のとおりです。

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を使用して) ミラー効果を追加し、再度呼び出すことができます。transformscaletranslate

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 に答える