I want to draw a diamond using paper.js. The shape and colors of the diamond should change randomly everytime I re-run the function. How do i go about this task
Asked
Active
Viewed 374 times
2 Answers
2
Here is a sketch demonstrating a possible implementation.
// Diamond random size settings
const MIN_RADIUS = 10;
const MAX_RADIUS = 50;
// Draw first diamond.
let diamond = drawDiamond(view.center);
// Display instructions.
new PointText({
content: 'Click to draw a new diamond',
point: view.center + [0, -80],
justification: 'center'
});
// Draws a random diamond around the given point and returns it.
function drawDiamond(point) {
// Get random radiuses.
const verticalRadius = getRandomRadius();
const horizontalRadius = getRandomRadius();
// Calculate diamond points.
const top = point + [0, -verticalRadius];
const bottom = point + [0, verticalRadius];
const left = point + [-horizontalRadius, 0];
const right = point + [horizontalRadius, 0];
// Build path.
return new Path({
segments: [top, right, bottom, left],
fillColor: Color.random()
});
}
function getRandomRadius() {
return MIN_RADIUS + Math.random() * (MAX_RADIUS - MIN_RADIUS);
}
// On mouse down...
function onMouseDown() {
// ...delete existing diamond...
diamond.remove();
// ...and draw a new one.
diamond = drawDiamond(view.center);
}

sasensi
- 4,610
- 10
- 35
0
var diamond = new Path.RegularPolygon(new Point(x,y), 4, 50);
diamond.fillColor = '#e9e9ff';
diamond.selected = true;
diamond.rotate(45);
x,y -> your coordinates
to generate random color have a look at this Random color generator
as of your final code should look something like this
function diamonds(){
var diamond = new Path.RegularPolygon(new Point(x,y), 4, 50);
diamond.fillColor = getRandomColor();
diamond.selected = true;
diamond.rotate(45);
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

pavan kumar
- 823
- 6
- 15