使用canvas Javascript绘制正方形

Dal*_*las 5 javascript 2d canvas drawing2d

制作一个用于分配的随机艺术生成器。我们应该随机弹出正方形,但我不知道如何绘制正方形。这就是我到目前为止所拥有的

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)
 }
Run Code Online (Sandbox Code Playgroud)

xia*_*glu 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');
Run Code Online (Sandbox Code Playgroud)
<canvas width=300 height=300 id="canvas" ></canvas>
Run Code Online (Sandbox Code Playgroud)