1 /* 2 * Copyright 2014 Google Inc. 3 * 4 * 5 * Use of this source code is governed by a BSD-style license that can be 6 * found in the LICENSE file. 7 * 8 */ 9 10 #ifndef SkV8Example_JsContext_DEFINED 11 #define SkV8Example_JsContext_DEFINED 12 13 #include <v8.h> 14 15 #include "SkPaint.h" 16 #include "DrawingMethods.h" 17 18 class SkCanvas; 19 class Global; 20 21 // Provides the canvas context implementation in JS, and the OnDraw() method in 22 // C++ that's used to bridge from C++ to JS. Should be used in JS as: 23 // 24 // function onDraw(context) { 25 // context.fillStyle="#FF0000"; 26 // context.fillRect(x, y, w, h); 27 // } 28 class JsContext : public DrawingMethods { 29 public: JsContext(Global * global)30 JsContext(Global* global) 31 : INHERITED(global) 32 , fCanvas(NULL) 33 { 34 } ~JsContext()35 virtual ~JsContext() {} 36 37 // Parse the script. 38 bool initialize(); 39 40 // Call this with the SkCanvas you want onDraw to draw on. 41 void onDraw(SkCanvas* canvas); 42 getCanvas()43 virtual SkCanvas* getCanvas() { return fCanvas; }; 44 45 private: 46 47 // Wrap the 'this' pointer into an Object. Can be retrieved via Unwrap. 48 v8::Handle<v8::Object> wrap(); 49 50 // A handle to the onDraw function defined in the script. 51 v8::Persistent<v8::Function> fOnDraw; 52 53 // The template for what a canvas context object looks like. The canvas 54 // context object is what's passed into the JS onDraw() function. 55 static v8::Persistent<v8::ObjectTemplate> gContextTemplate; 56 57 // Only valid when inside OnDraw(). 58 SkCanvas* fCanvas; 59 60 typedef DrawingMethods INHERITED; 61 }; 62 63 #endif 64