xxxxxxxxxx
90
// starting x and y values
let startX = 0;
let startY = 0;
// end points for the line
let endX = 0;
let endY = 0;
// line object
let myLine;
// array to hold the line objects
let lines = []
function setup() {
createCanvas(400, 400)
// change this value for a thinner or thicker line
strokeWeight(10)
// This changes color or makes grayscale
// Currently is a red line
stroke(255, 0, 0)
}
function draw() {
background(220);
// each time you click and drag the mouse, a new
// line is drawn on the canvas
for (i = 0; i < lines.length; i++) {
lines[i].display()
}
}
function mousePressed() {
// set the line start point where you first press the mouse
startX = mouseX;
startY = mouseY;
// Initially set end point equal to start point
endX = mouseX;
endY = mouseY;
// Create a new line object
myLine = new Line(startX, startY, endX, endY)
// Add the line object to the lines array
lines.push(myLine)
}
function mouseDragged() {
// update the end of the line to where the mouse is dragged
let diffX = mouseX - startX
let diffY = mouseY - startY
endX = startX + diffX
endY = startY + diffY
// Update the line endpoint
myLine.setEndPoint(endX, endY)
}
class Line {
// create a new line
constructor(x1, y1, x2, y2) {
this.x1 = x1
this.y1 = y1
this.x2 = x2
this.y2 = y2
}
// display the line on the canvas
display() {
line(this.x1, this.y1, this.x2, this.y2)
}
// set the end point of the line to new values
setEndPoint(x, y) {
this.x2 = x
this.y2 = y
}
}