如何一次在画布上绘制多个项目?

时间:2018-09-23 20:55:03

标签: javascript html html5-canvas

我正在尝试创建在整个画布上随机生成的多个圆圈(游戏的食物)。

<html>
	<!DOCTYPE HTML>
	<meta charset="UTF-8" name="viewport" content="width=device-width">
	<head>
		<title>Circle</title>
	</head>
	<body>
	<canvas id="circ"></canvas>
	<script type="text/javascript">
		var circ=document.getElementById("circ");
		var ctx=circ.getContext("2d");
		var colors=["blue", "red", "green", "purple", "pink", "yellow"]; //colors to use for the food
		
	   	foodPosX=(Math.random()*300); //getting a random x coord
    	foodPosY=(Math.random()*150); //get a random y coord

		for (food=0; food<10; food++) { // if food is less than 10 then add more food
		    ctx.arc(foodPosX, foodPosY, randInt(3,6), 0, 2*Math.PI); //drawing a circle for the food
            ctx.fillStyle= colors[randInt(0,7)]; // choose random color from var colors
            ctx.fill(); //fill the circle with the color
		}

		function randInt(min, max) { //gets a random integer between whatever values you need
   			min=Math.ceil(min);
    		max=Math.floor(max);
    		return Math.floor(Math.random()*(max-min))+min;
		}

	</script>
	<style>
		#circ {
			border: 1px solid black;
		}
	</style>
</body>
</html>

我已经尝试寻找解决方案已有一段时间了,似乎无法弄清楚。我尝试了getImageData,但不确定如何针对我的特定情况使用它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

由于foodPosXfoodPosY仅设置了一次,您当前正在做的是在同一位置绘制10个圆。

foodPosX=(Math.random()*300);循环内移动foodPosY(和for)。
您还需要添加ctx.beginPath();,否则将在圆之间绘制“弧”,这看起来很奇怪。

<html>
	<!DOCTYPE HTML>
	<meta charset="UTF-8" name="viewport" content="width=device-width">
	<head>
		<title>Circle</title>
	</head>
	<body>
	<canvas id="circ"></canvas>
	<script type="text/javascript">
		var circ=document.getElementById("circ");
		var ctx=circ.getContext("2d");
		var colors=["blue", "red", "green", "purple", "pink", "yellow"]; //colors to use for the food

		for (food=0; food<10; food++) { // if food is less than 10 then add more food
		    foodPosX = Math.random()*300; //getting a random x coord
		    foodPosY = Math.random()*150; //get a random y coord
		    ctx.beginPath();
		    ctx.arc(foodPosX, foodPosY, randInt(3,6), 0, 2*Math.PI); //drawing a circle for the food
		    ctx.fillStyle = colors[randInt(0,7)]; // choose random color from var colors
		    ctx.fill(); //fill the circle with the color
		}

		function randInt(min, max) { //gets a random integer between whatever values you need
		  min=Math.ceil(min);
		  max=Math.floor(max);
		  return Math.floor(Math.random()*(max-min))+min;
		}

	</script>
	<style>
		#circ {
			border: 1px solid black;
		}
	</style>
</body>
</html>