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)
}
The rect() method creates a rectangle. Tip: Use the stroke() or the fill() method to actually draw the rectangle on the canvas.
<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With