试图制作一排具有与画布宽度成比例的随机宽度的砖块

时间:2015-12-01 21:29:21

标签: javascript html5 math canvas

我正在尝试绘制一排砖块

  • 砖应该有随机长度
  • 砖块不应伸出画布。
  • 画布长度为400,我希望在10 px每侧的行和画布之间有填充
  • 每块砖之间应该有10个像素的填充(或者更好,因为用户可以输入大量的35像素,你可以使填充变小像2 px [可选])

在这个错误的代码中,您看到我尝试创建7块砖drawRow(7)。它们具有随机大小,但它们与画布的宽度减去画布填充量不成比例。并且他们在砖块之间没有10个px填充物。这是一个数学问题,我无法弄清楚比例可能。任何帮助都会很有意义。

$(function(){
	var canvas = $("canvas")[0],
		context = canvas.getContext("2d"),
		cWidth = canvas.width,
		brickHeight = 20,
		canvasPadding = 10,
		lengthOfRow = cWidth - 20 *2,
		width = 0,
		x = canvasPadding,
		brickPadding = 10;

	function drawBrick(x,y,w,h){
		context.beginPath();
		context.rect(x,y, w, h)
		context.fillStyle = "red";
		context.fill()
		context.strokeStyle = "black"
		context.stroke()
		context.closePath()
	}

	function drawRow(num){
		
			
			// width = 50;
			for(var i = 0; i < num; i ++){
				if(x + width < lengthOfRow + width){
					// x= x + width + brickPadding;
					var numOfBlocks = lengthOfRow / num;
					width = Math.floor(Math.random() * ((numOfBlocks + 10 - (numOfBlocks)  + 1) +  (numOfBlocks -10) )) 
					x = i * (width  + width /brickPadding)
					
					drawBrick(x +canvasPadding ,0,width * 2,brickHeight)
					// width += width;
				// x += x
				console.log(x, " ", width, " numblock ", numOfBlocks)
				}

			}
	}

	drawRow(7)

})
background: #ece;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<canvas id="canvas" width="400" height="400"></canvas>

1 个答案:

答案 0 :(得分:2)

您的drawRow()函数使用单个循环来计算随机砖宽度并绘制砖块。但是,在知道单个砖宽度与所有砖宽度之和的比率之前,无法计算单个砖块宽度。我建议使用两个循环。在第一个循环中,计算每个砖的随机数并将这些随机数相加。您现在可以计算单个砖宽度与砖宽度之和的比率(例如,砖的随机数除以随机数的总和)。在第二个循环中,计算砖块宽度并绘制砖块。个人砖的宽度等于砖的宽度乘以砖的总和的总和。所有砖宽度的总和是画布宽度减去画布填充的总和减去砖填充的总和。例如,代码可能看起来像......

$(function() {

    var canvas = $("canvas")[0],
        context = canvas.getContext("2d"),
        canvasWidth = canvas.width,
        canvasPadding = 10,
        brickPadding = 10,
        brickY = 0,
        brickHeight = 20;

    function drawBrick(x, y, w, h) {
        context.rect(x, y, w, h)
        context.fillStyle = "red";
        context.fill()
        context.strokeStyle = "black"
        context.stroke()
    }

    function drawRow(num){
        var brickX = canvasPadding;
        var brickRandom = [];
        var sumBrickRandom = 0;
        var sumBrickWidths = canvasWidth - 2 * canvasPadding - (num - 1) * brickPadding;
        for (var i = 0; i < num; i++) {
            var randomNumber = 1 + 3 * Math.random();
            brickRandom[i] = randomNumber;
            sumBrickRandom += randomNumber;
        }
        for(var i = 0; i < num; i++) {
            var brickWidth = sumBrickWidths * brickRandom[i] / sumBrickRandom;
            drawBrick(brickX, brickY, brickWidth, brickHeight);
            brickX += brickWidth + brickPadding;
        }
    }

    drawRow(7);

});

请注意,我生成了1到4之间的随机数。这样可以确保最大宽度不超过最小宽度的4倍。这避免了最小宽度可能接近零的情况。