Reputation: 27
I need to randomize the coordinates of shapes. I know I need to somehow introduce the Math.floor(Math.Random * num); line in there, but nothing I do seems to work.
This is the block with the filled in coordinates I am trying to randomize.
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.lineWidth="5";
ctx.strokeStyle="black";
ctx.moveTo;
ctx.lineTo(100,20);
ctx.lineTo(30,400);
ctx.lineTo(300,40);
ctx.lineTo(10,20);
ctx.stroke();
I've searched and searched and found nothing directly on this for some reason. Sorry this is such a basic question too, I'm really new to this and still learning the basics.
Thank you in advance
Upvotes: 2
Views: 74
Reputation: 1592
Here is a fiddle showing the things I explain below.
Check this page for syntax regarding the Canvas.
If you want to be able to quickly and easily designate random coordinates, you can wrap it up in a function.
function randCoord(factor){
return Math.random() * factor;
}
and then use it like this:
// all of these will go to different points
ctx.moveTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
ctx.lineTo(randCoord(300),randCoord(100));
You could set a default scale:
function randCoord(factor){
if (factor == undefined){
factor = 100;
}
return Math.random() * factor;
}
Which would allow you to simply write the function name.
ctx.lineTo(randCoord(),randCoord());
You can also make another function that just adds a random additional point
function addRandomPoint(xFactor, yFactor) {
ctx.lineTo( randCoord(xFactor), randCoord(yFactor) );
}
// these will all add new points
addRandomPoint();
addRandomPoint();
addRandomPoint(200, 300);
addRandomPoint(-100, 25);
And then wrap it up in loop to make many points
// this will add 10 new points
for (var i = 0; i < 10; i++) {
addRandomPoint();
}
So you could do this:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.lineWidth="5";
ctx.strokeStyle="black";
ctx.moveTo(10, 10);
for (var i = 0; i < 10; i++) {
addRandomPoint();
}
ctx.stroke();
Upvotes: 1