我正在p5.js中通过鼠标学习用户输入,我想在4次不同的单击上创建4行平方的方法,每行1次单击,最后一次单击完成平方。 下面的代码适用于2行,但是都同时运行,因此我无法理解if命令单独运行它们。
function setup() {
createCanvas(400, 400);
background(220);
}
function draw() {
}
function mousePressed()
{
line(width/20,height/40,mouseX,mouseY);
line(pmouseX,pmouseY,mouseX,mouseY);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
答案 0 :(得分:0)
您必须将点存储到列表中。如果列表包含4个元素,并且再次单击鼠标,请清除列表:
var pts = [];
function mousePressed()
{
if (pts.length == 4) {
pts = [];
}
pts.push([mouseX, mouseY])
}
在draw()
中连续绘制所有图形。清除背景。在一个循环中在点之间绘制留置权。如果点数为4,则从最后一个点到第一个点画一条线。
另外,如果列表中至少有1个点,则可以从最后一个点到当前鼠标位置绘制一条“橡胶”线:
function draw() {
background(220);
// draw the lines between the points
for (var i=0; i < pts.length-1; ++i) {
line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]);
}
var close = pts.length == 4;
if (close) {
// draw line from 1st point to at point
line(pts[pts.length-1][0], pts[pts.length-1][1], pts[0][0], pts[0][1]);
}
else if (pts.length > 0) {
// draw a rubber line from last point to the mouse
line(pts[pts.length-1][0], pts[pts.length-1][1], mouseX,mouseY);
}
}
查看示例
function setup() {
createCanvas(400, 400);
}
var pts = [];
function mousePressed()
{
if (pts.length == 4) {
pts = [];
}
pts.push([mouseX, mouseY])
}
function draw() {
background(220);
// draw the lines between the points
for (var i=0; i < pts.length-1; ++i) {
line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]);
}
var close = pts.length == 4;
if (close) {
// draw line from 1st point to at point
line(pts[pts.length-1][0], pts[pts.length-1][1], pts[0][0], pts[0][1]);
}
else if (pts.length > 0) {
// draw a rubber line from last point to the mouse
line(pts[pts.length-1][0], pts[pts.length-1][1], mouseX,mouseY);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>