I want to draw lines as I click on the canvas, so if I clicked once then save the point, and if I clicked the second time then draw a line behind these two points. But, I want to make this multiple times, so, If I clicked the third time then this point will be the starting point of a new line.
I created like this:
This is in the main
:
ArrayList<Shape> shapes = new ArrayList<Shape>();
Shape selected_shape = null;
Boolean drawmode = true;
void setup() {
size(1000, 600);
}
void draw() {
//update();
background(224, 224, 224);
//draw the existing
for(Shape s: shapes){
pushMatrix();
//list all
s.Draw();
s.Log();
popMatrix();
}
println("shape size: "+shapes.size());
}
//menu
int value = 0;
void keyPressed() {
if(key == '0'){
System.out.println("Draw mode OFF"); // exit from draw mode
value = 0;
}
if(key == '1'){
println("Draw a line: select the start point of the line and the end point!"); // line
value = 1;
}
//System.out.println("key: " + key);
}
Line l = new Line();
void mousePressed() {
if(value == 1){
if(l.centerIsSet){
if (mouseButton == LEFT) {
l.x2 = mouseX;
l.y2 = mouseY;
println("end point added");
l.centerIsSet = false;
}
shapes.add(l);
l.Log();
} else {
if (mouseButton == LEFT) {
l.x1 = mouseX;
l.y1 = mouseY;
l.centerIsSet = true;
println("start point added");
}
}
}
}
And I use a shape
class and this class is extended with line
:
abstract class Shape {
PVector position = new PVector();
PVector fill_color = new PVector(0, 0, 0);
PVector stroke_color = new PVector(0, 0, 0);
PVector select_fill_color = new PVector(255, 0, 0);
PVector select_stroke_color = new PVector(255, 0, 0);
Boolean selected = false;
int shape_color_r;
int shape_color_g;
int shape_color_b;
int shape_rotation_angle = 0;
int detailness = 10;
abstract void Draw();
abstract void Log();
}
and:
class Line extends Shape {
int x1, x2, y1, y2;
Boolean centerIsSet = false;
Line(){}
Line(int x1, int y1){
this.x1 = x1;
this.y1 = y1;
}
Line(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
void Draw(){
line(x1, y1, x2, y2);
}
void Log(){
System.out.println("x1: "+x1+" x2: "+x2+" y1: "+y1+" y2: "+y2);
}
}
But always the last created line overwrite the old ones, how can I resolve this? I think I need a new instance for each line, but I don't know how can I do this.
The variable l
refers to the Line
object which holds the coordinates of the line which is currently drawn.
If you have finished a line, then the reference to line object l
is add to the container shapes
. Now you have to create a new line object, for the next line and assign it to l
:
shapes.add(l);
l = new Line();