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

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

1
你可以将你的图形代码放到一个函数中,只需调用一次,然后使用另一个状态 (save, restore) 来添加镜像效果(使用 transform 或者 scale+translate),再次调用该函数即可。详情请见 https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial/Transformations - Zeta
@Zeta:你应该把你的解决方案写成一个答案。 - Ammar
@Ammar:我觉得我没有足够的时间来写一个详细的答案。我喜欢在提交答案之前测试它们并提供一些演示。 - Zeta
1个回答

5
您可以将形状放入一个函数中,调用一次,然后使用另一个状态(saverestore)添加镜像效果(使用 transform scale+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:变换以获取示例。

谢谢先生。虽然我开始觉得我应该找出这个形状另一半的坐标并摆脱这个复杂性 :) - Jeremy Smith

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