javascript - 在 Canvas 上绘制更多内容而无需创建更多脚本标签

标签 javascript html canvas

我一直在尝试创建一个生态模拟,到目前为止一切顺利。下面的代码确实有效我只是想知道是否有一种更简单的方法可以用代码在 Canvas 上绘制更多项目而不是手动执行。我这样做的方式让我考虑到延迟,因为我将向代码中添加很多内容(例如移动、检测、复制、追逐、运行等)。谢谢你看到这个

//This tag will regulate the spawning of new sheep/wolves
var totalWolves = 0;
var totalSheep = 0;
var canavs = document.getElementById("canvas");
var body = document.getElementById("body");

//styler
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";

function spawnWolves(){
	totalWolves++;
	var name = "wolf" + totalWolves;
	var scrpt = document.createElement("SCRIPT");
	document.body.appendChild(scrpt);
	scrpt.setAttribute("id", name);
	var script = document.getElementById(name);
	script.innerHTML = "var rand3 = Math.floor(Math.random() * 100) + 1; var rand4 = Math.floor(Math.random() * 100) + 1; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = 'red'; context.fillRect(rand3, rand4, 10, 10); context.fill();";
	
}
spawnWolves();
spawnWolves();
spawnWolves();
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
<script>

</script>
</body>
</html>

最佳答案

你的解决方案看起来很复杂......

请看下面的代码。

  <!DOCTYPE html>
  <html>
  <title>AI spawn test</title>
  <canvas id="canvas" width="110" height="110"></canvas>
  <script>
  var ctx = canvas.getContext("2d");
  var drawRect=function(rects){
    for (var i=1; i<=rects; i++){
      var rand3=Math.floor(Math.random() * 100) + 1;
      var rand4=Math.floor(Math.random() * 100) + 1;
      ctx.fillStyle='red';
      ctx.fillRect(rand3, rand4, 10, 10)
    }
  }
  drawRect(20);
  </script>

关于javascript - 在 Canvas 上绘制更多内容而无需创建更多脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44216156/

相关文章:

javascript - 无法访问 html5 Canvas ?

javascript - 一种方式流式传输 - 在添加候选项之前 ICE 连接失败

javascript - 更改网站中启用的div,而无需重新加载页面(说明中的特定示例)

javascript - 如何用显示 :none tags? 包装类

javascript - 如何使用 HTML5 canvas 标签显示视频

javascript - 在 HTML5 canvas 中创建关键事件的最佳方式是什么?

javascript - 谷歌日历用户界面

javascript - CKEditor格式类

javascript - 在文本框中获取选定的文本

html - 为什么我最近的帖子框的文本会溢出?