dimanche 19 juin 2016

How to draw multiple random obects using canvas in javascript

Using canvas I need to create other random shapes to appear in random sizes and random locations. So far I have random circles. But I cant Figure out how to get other shapes as well.

in the body i have

<canvas width='600' height='200' id='artCanvas'></canvas>
<form>
<input type='button' id='artButton' value='New Masterpiece'>
</form>

Using this code I need to create multiple other shapes in the same way the circles are being created randomly.

<script>
function makeTitle() {
//generate the title for your masterpiece
var lines =[['Meditative','Objective','Reflective'['Ellipses','Tranformation', 'State', 'Emotion', 'Composition']['I', 'II', 'III', 'IV','V']];
var title = '';
for (var i=0; i<lines.length; i++) {
var random = Math.floor(Math.random() * lines[i].length);
title += lines[i][random] + ' ';
};
return(title);
}
function artHandler() {
var title = makeTitle();
alert(title);
var canvas = document.getElementById('artCanvas');
var context = canvas.getContext('2d');
fillBackgroundColor(canvas, context);
var colors = ['white', 'yellow', 'blue', 'red'];
for (var i = 0; i < 20; i++) {
var color = colors[Math.floor(Math.random() * colors.length)];
drawCircle(canvas, context, color); 
}
drawText(canvas, context, title);
}
function fillBackgroundColor(canvas, context) {
var colors = ['white', 'yellow', 'blue', 'red'];
var bgColor = colors[Math.floor(Math.random() * colors.length)];
context.fillStyle = bgColor;
context.fillRect(0, 0, canvas.width, canvas.height);
}
function degreesToRadians(degrees) {
return (degrees * Math.PI)/180;
}
// Draws a circle at a random location
function drawCircle(canvas, context, color) {
var radius = Math.floor(Math.random() * 40);
var x = Math.floor(Math.random() * canvas.width);
var y = Math.floor(Math.random() * canvas.height);
context.beginPath();
context.arc(x, y, radius, 0, degreesToRadians(360), true);
context.fillStyle = color;
context.fill();
}
function drawText(canvas, context, title) {
context.fillStyle = 'black';
context.font = 'bold 1em sans-serif';
context.textAlign = 'right';
context.fillText(title, canvas.width-20, canvas.height-40);
}
window.onload = function() {
var button = document.getElementById('artButton');
button.onclick = artHandler;
}
</script>




Aucun commentaire:

Enregistrer un commentaire