gpt4 book ai didi

javascript - 如何克隆/概括 Canvas 绘图

转载 作者:行者123 更新时间:2023-12-03 04:42:23 28 4
gpt4 key购买 nike

我正在做一个 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 (我需要间隙,这样激光就会穿过它们)。

This is the conception

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

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

我是所有这一切的新手。

最佳答案

下面是使用“矩形”的 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>

关于javascript - 如何克隆/概括 Canvas 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43028801/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com