2017-09-16 261 views
2

單擊畫布時,是否可以在p5 js草圖中調用function draw(){}通過鼠標點擊呼叫功能

我希望繪製函數下的所有東西在點擊畫布上的任何位置時被調用,而不是在之前。

function setup() { 
 
createCanvas(500, 500); 
 
frameRate(65); 
 
    background('#ff0a0a'); 
 
textSize(60); 
 
text("ART", 370, 250); 
 

 
}; 
 
function draw() { 
 
    noFill(); 
 
    var red = random(100); 
 
    var green = random(200); 
 
    var blue =random(230); 
 
    var h = random(height); 
 

 
    stroke(red,green,blue); 
 
    strokeWeight(8); 
 
    rect(frameCount,h,300,20+(frameCount)); 
 
    
 
    ellipse(frameCount,h ,300,20+(frameCount)); 
 
    triangle(frameCount,h ,300,20+(frameCount)); 
 

 
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.js"></script>

+0

你並不需要調用'平局()'函數自己。它每秒自動調用60次。你究竟想要做什麼?你可以請張貼[mcve]嗎? –

+0

是的,我會編輯我原來的問題。 – codeneophyte

+0

發佈代碼段時,請確保包含圖書館。查看我剛剛編輯的內容。 –

回答

1

這對我工作得很好:

function setup() { 
 
    createCanvas(500, 500); 
 
    frameRate(65); 
 
    background('#ff0a0a'); 
 
    textSize(60); 
 
    text("ART", 370, 250); 
 
}; 
 

 
function mousePressed() { 
 
    noFill(); 
 
    var red = random(100); 
 
    var green = random(200); 
 
    var blue =random(230); 
 
    var h = random(height); 
 

 
    stroke(red,green,blue); 
 
    strokeWeight(8); 
 
    rect(frameCount,h,300,20+(frameCount)); 
 
    
 
    ellipse(frameCount,h ,300,20+(frameCount)); 
 
    triangle(frameCount,h ,300,20+(frameCount)); 
 
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.js"></script>

+0

不錯謝謝!有沒有辦法讓它如此,當我點擊一次它會連續繪製,而不必點擊多次? – codeneophyte

+0

@codeneophyte您是否嘗試過'mouseDragged()'函數,或者檢查是否從draw()函數中按下鼠標? –

+0

不,我沒有意識到'mouseDragged'函數,但我現在已經嘗試過了,它完全符合我的要求。謝謝你的幫助! – codeneophyte

0

剛剛提到了另一種方法來解決你的問題Kevin's answer上面,你可以這樣做像這樣,當鼠標我連續畫點擊一次,再次點擊時停止。這工作就像一個撥動開關用於繪圖: -

var drawThings; 
 

 
function setup() { 
 
    createCanvas(500, 500); 
 
    frameRate(65); 
 
    background('#ff0a0a'); 
 
    textSize(60); 
 
    text("ART", 370, 250); 
 
} 
 

 
function draw() { 
 
    if (drawThings) { 
 
    noFill(); 
 
    var red = random(100); 
 
    var green = random(200); 
 
    var blue = random(230); 
 
    var h = random(height); 
 

 
    stroke(red, green, blue); 
 
    strokeWeight(8); 
 
    rect(frameCount, h, 300, 20 + (frameCount)); 
 

 
    ellipse(frameCount, h, 300, 20 + (frameCount)); 
 
    triangle(frameCount, h, 300, 20 + (frameCount)); 
 
    } 
 
} 
 

 
function mouseClicked() { 
 
    drawThings = !drawThings; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.14/p5.js"></script>

+0

爲什麼你不只是使用'mouseIsPressed'變量?請注意,我已在評論中解釋了此選項。 –

+0

@KevinWorkman因爲那不會實現切換繪製效果,這會讓你保持畫效果 –

+0

我以爲OP在尋找壓制效果。無論如何,還要注意你可以將你的'mouseClicked()'函數縮短爲'drawThings =!drawThings;' –