如何 clone/generalize canvas 绘图

How to clone/generalize a canvas drawing

我正在做 JavaScript 游戏作业,只是尝试 canvas 玩了一会儿。我的任务是用激光源、镜子和目标对象进行激光游戏。

我刚刚制作了一个丑陋的硬编码示例:

'use strict';

function $(id) {
    return document.getElementById(id);
}

function draw() {
    let canvas = $('canvas');
    if(canvas.getContext) {
        let ctx = canvas.getContext("2d");
        ctx.lineWidth = 5;
        ctx.strokeStyle = 'hsla(265, 18%, 26%, 0,80)';

        ctx.beginPath();
        ctx.moveTo(10,10);
        ctx.lineTo(10,60);
        ctx.moveTo(10,65);
        ctx.lineTo(10,115);
        ctx.moveTo(10,115);
        ctx.lineTo(60,115);
        ctx.moveTo(65,115);
        ctx.lineTo(115,115);
        ctx.moveTo(115,115);
        ctx.lineTo(115,65);
        ctx.moveTo(115,60);
        ctx.lineTo(115,10);
        ctx.moveTo(115,10);
        ctx.lineTo(65,10);
        ctx.moveTo(60,10);
        ctx.lineTo(10,10);          
        ctx.stroke();
    }
}

draw();  

https://jsfiddle.net/h9664oz4/

我的问题是:你会建议什么解决方案,这样我就可以用这样的矩形制作一个 N*N table(我需要间隙,所以激光会穿过它们)。

我需要将元素放在矩形内,但我希望激光路径的每一侧都有 2 个间隙,而不是在中间。这只是为了澄清。

说清楚,我不想要现成的解决方案,我想学习。只想要一些指导,继续前进。你会建议深入研究 SVG 吗?这些 2D 游戏是否有一些 JS 模式约定?您会推荐使用 类 来获得更清晰的代码架构吗?

我是这一切的新手。

下面是一个使用您的 'rectangles' 的 SVG 示例,它是一个 SVG 路径元素。创建要克隆的路径并将其放置在 SVG defs 元素中。

<!DOCTYPE HTML>
<html>
<head>
  <title>Cloned Paths</title>
</head>

<body onload=clonePaths()>
<div id="svgDiv" style='background-color:lightgreen;width:400px;height:400px;'>
<svg id="mySVG" width="400" height="400">
<defs id=myDefs />
</svg>
</div>
<script>
 var NS="http://www.w3.org/2000/svg"
//---onload---
function clonePaths()
{
    //---create path for cloning---
    var myPath=document.createElementNS(NS,"path")
    myPath.id="pathClone"
    myPath.setAttribute("stroke-width",2)
    myPath.setAttribute("stroke","black")
    myPath.setAttribute("fill","none")
    var d="M10,10 L10,60 M10,65 L10,115 M10,115 L60,115 M65,115 L115,115 M115,115 L115,65 M115,60 L115,10 M115,10 L65,10 M60,10 L10,10"
    myPath.setAttribute("d",d)
    myDefs.appendChild(myPath)

    //---add clones---
    var pathClone=document.getElementById("pathClone")

    var path1=pathClone.cloneNode(true)
    path1.setAttribute("transform","translate(40,40)")
    mySVG.appendChild(path1)

    var path2=pathClone.cloneNode(true)
    path2.setAttribute("transform","translate(40,160)")
    mySVG.appendChild(path2)

    var path3=pathClone.cloneNode(true)
    path3.setAttribute("transform","translate(40,280)")
    mySVG.appendChild(path3)

}
</script>
</body>

</html>