p5.j​​s:在draw之外绘制一个元素

时间:2018-06-09 01:40:21

标签: javascript p5.js

我的问题很简单。在p5.js中,有一个绘制函数。我认为你只能绘制元素(就像这个函数里面的一个矩形)。我想在一个外部绘制的函数中绘制一个矩形。 (仅由某些事件触发)。任何人都知道如何做到这一点?

编辑:尝试用rect(x,y,w,h)在外面画画不起作用 也尝试在draw()中制作一个this.drawRect = function(){},也没有运气

1 个答案:

答案 0 :(得分:0)

TL; DR:https://jsbin.com/widinuruna/edit?html,css,js,output

function setup() { 
  createCanvas(400, 400);
  noLoop() // make draw to only be called once
} 

function draw() { // usually called 60 times / s
  background(220); // clears the canvas (including your rect, if drawn before)
}

setTimeout(()=> {
  rect(20,20,50,50)
}, 300)

你的矩形可能在你看到之前画出来了:)

参考:https://p5js.org/reference/#/p5/draw

让我们说一下在鼠标按下时光标处的方框。根据您的使用情况,您可能希望:

  • 不断重绘所有内容

    // try changing 60 to eg. 1, and click fast while moving the cursor
    // - you'll see it will still only update once a second
    function setup() {
      createCanvas(400, 400)
      frameRate(60) // make draw be called 60 times/s (default?)
    }
    // keeping "state" as an object is a common practice... 
    const state = {x: 0, y: 0} // initialize state
    // ...then it can be updated whenever, eg. on interaction,
    //  without caring about the drawing
    function mousePressed() {
      // update state on interaction
      state.x = mouseX; state.y = mouseY
    }
    // ...the screen will then update independently
    function draw() {
      // (avoid changing the state here)
      background(220) // clear the canvas
      rect(state.x, state.y, 50, 50) // draw according to state
    }
    // by separating "logic" (eg. changing the state) and drawing:
    //  - a "game" will "behave" the same even at different fps,
    //    important for multiplayer etc.
    //  - code will be simpler to reason about and work with, etc
    
  • 仅在必要时重绘

    // using noLoop() in setup, draw() will only be called once initially
    // then, either use rect in eg. mousePressed, or:
    // keep using state, but manually call redraw() after changing the state
    pros = "more efficient if less redraws then eg. 60fps is needed"
    cons = "need to know when to invoke redraw,"
         + "possibly makes code a bit more complicated"
    
  • 只重绘必要的内容

    // using either point 1 or 2, but in addition keeps track of the
    // previous state, then, only redraws the part of the screen necessary
    // eg. instead of calling background(200), which is the same as:
    fill(200); rect(0,0,width,hight); fill(255) // to clear the screen (and restore fill color)
    fill(200); rect(oldState.x,oldState.y,50,50); fill(255) // clearing only what was previously drawn
    /* followed by */ rect(state.x,state.y,50,50); // as normal
    // (assumes noStroke() is called in setup)
    pros = "possibly much more efficient if large canvas"
    cons = "possibly more complicated"