Drawing square using canvas Javascript
Asked Answered
P

3

6

Making a random art generator for assignment. We are supposed to have squares randomly pop up but I can't figure out to draw a square. This is what I have so far

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)
 }
Panel answered 13/4, 2018 at 0:52 Comment(6)
looks almost right, although you don't need beginPath for this, as it is just a fill not a stroke. You want to set the width/height of the rectangles much smaller, whereas now you are making the rects as big as the canvas. Next step is to call drawSquare for as many squares as you want to draw, so you could use a for loop.Domitian
@Noface thank you! so I should change x and y to math.floor(Math.random()*20 ); or something like that to set the size?? and would .fillrect (x,y,width,width) work since a square is the same size?Panel
@Noface also so far as calling for it we are supposed to randomly for every iteration of your for loop, it should choose randomly if it draws a circle or a square... so right now in my function I have... for (var i=0; i<20; i++) ...... drawCircle(canvas,context,color). if (Math.random() < .4 ) { drawCircle(canvas,..,color) else { drawSquare..... am I on the right track?Panel
yes, 20 meaning 20 pixels. and setting height to the same as width would indeed make a square. You could also set the size relative to the screen width or height, say 10% of the screen width would be window.innerWidth*0.1 - which would turn out to be some amount of pixels (varying depending on the screen width). Yes, call Math.random() to generate a new random number between > 0 and <= 1. You do not need to use Math.floor by the way.Domitian
@Noface Ok one last question, thank you new to javascript so I appreciate it...... do I need to call Math.random before i start my if function, or will that be when its called, for example I have: var colors = ['red','blue','green'] for (var i=0; i<40; i++){ var color = ..... if (Math.random() < 0.4) { drawCircle(canvas...color) else drawSquarePanel
I'm not sure what you mean, but if this helps: Math.random() will evaluate to a number, so you could imagine that it is just a number (between 0 and 1). So in the case of your if statement if (Math.random() < 0.4) { ... } else { ... } it will evaluate to some number like this: if (0.54462 < 0.4 ) { ... which then gets evaluated to either true or false. With that code it will evaluate to true about 40% of the time.Domitian
D
4

I don't like doing homework for people, but then again getting past the technical stuff and being able to get creative and artistic is the fun part. So, here is a random square generator you can play with, and learn from. There are some comments to explain it more.

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>
Domitian answered 13/4, 2018 at 1:33 Comment(0)
L
2

this is what you want?

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>
Lice answered 13/4, 2018 at 1:4 Comment(1)
bear in mind the rectangle gets cut off because the canvas width/height is too smallDomitian
S
2

As mentioned in the comments, you don't need to use paths for a solid rectangle. In this example I'm calling the function 600 milliseconds.

Edit:

These answers should both serve as helpful learning tools. Good luck!

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>
Switchblade answered 13/4, 2018 at 1:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.