使用Canvas JavaScript绘制正方形

5
制作一个随机艺术生成器的作业。我们需要让正方形随机弹出,但我不知道如何画正方形。目前我的代码是这样的:
function drawSquare(canvas, context, color){
    var x= Math.floor(Math.random()*canvas.width);
    var y= Math.floor(Math.random()*canvas.height);
    context.beginPath();
    context.fillStyle = color;
    context.fillRect (x,y, canvas.width, canvas.height)
 }

1
看起来几乎正确,但是你不需要为此使用beginPath,因为这只是填充而不是描边。你需要将矩形的宽度/高度设置得更小,而现在你正在将矩形设置为与画布一样大。下一步是调用drawSquare来绘制尽可能多的正方形,所以你可以使用for循环。 - George
@Noface谢谢!那我应该将x和y更改为math.floor(Math.random()*20);或类似的东西来设置大小吗?因为正方形是相同大小的,所以.fillrect(x,y,width,width)是否可行? - Dallas
@Noface,还有一个要求是我们应该在每次循环迭代时随机选择绘制圆形或正方形...所以现在在我的函数中,我有... for (var i=0; i<20; i++) ...... drawCircle(canvas,context,color)。如果 (Math.random() < .4 ) { drawCircle(canvas,..,color) else { drawSquare..... 我的想法正确吗? - Dallas
是的,20表示20像素。将高度设置为与宽度相同确实会生成一个正方形。您还可以根据屏幕的宽度或高度设置尺寸,例如屏幕宽度的10%将是window.innerWidth*0.1 - 这将转换为一定数量的像素(取决于屏幕宽度)。是的,调用Math.random()来生成一个介于> 0和<= 1之间的新随机数。顺便说一下,您不需要使用Math.floor - George
@Noface 好的,最后一个问题,谢谢。我是 JavaScript 新手,所以很感激。在开始 if 函数之前,我需要调用 Math.random 吗?还是当它被调用时才会执行?例如,我有以下代码:var colors = ['red','blue','green'] for (var i=0; i<40; i++){ var color = ..... if (Math.random() < 0.4) { drawCircle(canvas...color) } else { drawSquare(canvas...color) } } - Dallas
我不确定你的意思,但如果这有帮助的话:Math.random()将计算出一个数字,因此您可以想象它只是一个数字(介于0和1之间)。所以在您的if 语句 if (Math.random() < 0.4) { ... } else { ... } 的情况下,它将计算出像这样的一些数字:if (0.54462 < 0.4 ) { ... 然后被计算为truefalse。使用该代码,它将大约40%的时间计算为true。 - George
3个回答

3

我不喜欢为别人做作业,但是克服技术难点并能够发挥创造力和艺术感是有趣的部分。因此,这里有一个随机正方形生成器,您可以玩耍和学习。还有一些注释可以更好地解释它。

const canvas = document.getElementById("canv");
const ctx = canvas.getContext("2d");
const width = window.innerWidth;
const height = window.innerHeight;
const maxWH = Math.max(width, height);

//use resize event listener to change these on window resize...
canvas.width = width;
canvas.height = height;

//to generate random intergers from 0 to 255, for colour channels
function randomInteger(max = 256){
  return Math.floor(Math.random()*max);
}
//draw n squares at random places and sizes
function makeRandomSquares(n){
  for(let i = 0; i < n; i++){
    const size = Math.random()*(maxWH*0.15);
    //minus half the size from x,y
    //so they can overlap left and top of screen, not just bottom and right.
    const x = Math.random()*width-size/2;
    const y = Math.random()*height-size/2;
    //random rgba colour
    ctx.fillStyle = `rgba(${randomInteger()},${randomInteger()},${randomInteger()},${Math.random()*0.4})`;
    ctx.fillRect(x,y,size,size);
  }
}
//initialize with 2 squares
makeRandomSquares(2);
//make 2 more squares each click
document.addEventListener("click", function(){
  makeRandomSquares(2);
}, false);
html, body {
  margin: 0;
  padding: 0;
}
canvas {
  width: 100%;
  height: 100%;
}
<canvas id="canv"></canvas>


2

您需要的是这个吗?

function drawSquare(canvas, context, color){
    var x= Math.floor(Math.random()*canvas.width);
    var y= Math.floor(Math.random()*canvas.height);    
    context.fillStyle = color;
    context.fillRect (x,y, canvas.width, canvas.height)
 }
 
 let canvas=document.getElementById('canvas');
 drawSquare(canvas,canvas.getContext('2d'),'pink');
<canvas width=300 height=300 id="canvas" ></canvas>


请注意,矩形被裁剪掉是因为画布的宽度/高度太小。 - George

1

如评论中所述,对于实心矩形,您不需要使用路径。在此示例中,我将函数调用600毫秒。

编辑:

这些答案都应该作为有用的学习工具。祝你好运!

function randoRect() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  var color = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);

  function drawSquare(color) {
    var x = Math.floor(Math.random() * canvas.width);
    var y = Math.floor(Math.random() * canvas.height);
    ctx.fillStyle = color;
    ctx.fillRect(x, y, 40, 40);
  }

  drawSquare(color);

}

$('#start').on('click', function() {
  setInterval(randoRect, 600);
})
#start {
  background: coral;
  color: white;
  border: none;
  position: fixed;
  padding: 15px;
  top: 20px;
  left: 20px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">START</button>
<canvas id="canvas" width="630px" height="200px"></canvas>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接