Tegning med Processing.js
De to klassen i Processing-skissen er:
_sketch1.pde
/* Drawing simple lines Lines are ordered in strokes */ // thin line int strokeWidth=1; // all strokes ArrayList<pstroke> strokes; // and the one we are working on pstroke currentStroke=null; void setup() { size(300, 200); smooth(); frameRate(20); strokes=new ArrayList<pstroke>(); currentStroke=null; clearCanvas(); } void clearCanvas() { background(255, 255, 180); } //------------------------------------- // mousing // pressed mouse and we start a new stroke void mousePressed() { addStroke(strokeWidth); currentStroke.addpt(new PVector(mouseX, mouseY)); } // dragged and we add a point void mouseDragged() { if (currentStroke!=null) currentStroke.addpt(new PVector(mouseX, mouseY)); } void mouseReleased(){ currentStroke=null; } void draw() { clearCanvas(); for(pstroke s:strokes) s.drawStroke(); } // add a new stroke void addStroke(int strokeWidth) { currentStroke=new pstroke(strokeWidth); strokes.add(currentStroke); } // add a new point to current stroke void addPoint(int x, int y) { currentStroke.addpt(new PVector(x, y)); } // remove last stroke, called from javascript void removeLastStroke(){ if(!strokes.isEmpty()) strokes.remove(strokes.size()-1); } // set stroke width, called from js void setStrokeWidth(int w){ strokeWidth=w; }
_pstroke.pde
// hold a stroke with: // width and a series of points class pstroke { private int pwidth; // all the points in the stroke private ArrayList<PVector> pts; // constructor public pstroke(int pwidth) { this.pwidth=pwidth; this.pts=new ArrayList<PVector>(); } // add a point (no difflimit) public void addpt(PVector p) { pts.add(p); } // draw this stroke with all lines public void drawStroke() { // set color and width strokeWeight(this.pwidth); // loop points int ix=1; while (ix < pts.size ()) { line( pts.get(ix-1).x, pts.get(ix-1).y, pts.get(ix).x, pts.get(ix).y); ix++; } } }
Javascriptet som handterer valgene våre er slik:
_index.js
function clearDrawing(id){ var pjs = Processing.getInstanceById(id); pjs.setup(); } function setPenWidth(id,w){ var pjs = Processing.getInstanceById(id); pjs.setStrokeWidth(w); } function deleteLastStroke(id){ var pjs = Processing.getInstanceById(id); pjs.removeLastStroke(); }