简体   繁体   中英

Javascript p5 Unable to draw line between two points

In javascript, using p5, I want to draw a line between two points, set by the mouse. I'm using an array to store the mouse positions, then draw the line. However, I get a weird output when I log the array in the console.

这是控制台中的数组。前两个和最后两个元素是鼠标位置。

What would the " empty x 2 " mean? This is my code:

function mouseClicked(){
pointSize = slider.value();
stroke(color_picker.value());
strokeWeight(pointSize);
point(mouseX, mouseY);

if(selection === "line"){
   line_points.push(mouseX, mouseY);
   console.log(line_points);
   console.log(line_points.length);

    if(line_points.length = 4){
        line(line_points[0],line_points[1],line_points[2],line_points[3]);
        line_points = [];
    }
  }
}

The main issue in the code is the conditional

 if(line_points.length = 4)

should be

if(line_points.length ==== 4)

as we want to compare length to 4. The original code sets the length of the array to 4 which leaves the array with some empty positions, thus producing the empty slots message when the array is output to the console.

 function setup(){ const cnv = createCanvas(200, 200); } var line_points = []; function draw(){ } function mouseClicked(){ stroke(0); point(mouseX, mouseY); line_points.push(mouseX, mouseY); console.log(line_points); console.log(line_points.length); if(line_points.length === 4){ line(line_points[0],line_points[1],line_points[2],line_points[3]); line_points = []; } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM