Remove SkV8Example

Bug: skia:
Change-Id: I411787ae3ef7185e2909a683537799e51096fd62
Reviewed-on: https://skia-review.googlesource.com/74201
Reviewed-by: Greg Daniel <egdaniel@google.com>
This commit is contained in:
Brian Osman 2017-11-21 11:33:04 -05:00
parent 0860458333
commit 9e021d2441
20 changed files with 0 additions and 1860 deletions

View File

@ -1,172 +0,0 @@
/*
* Copyright 2014 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <v8.h>
#include "Global.h"
#include "DrawingMethods.h"
#include "Path2D.h"
#include "SkCanvas.h"
#include "SkPaint.h"
DrawingMethods* DrawingMethods::Unwrap(v8::Handle<v8::Object> obj) {
v8::Handle<v8::External> field = v8::Handle<v8::External>::Cast(obj->GetInternalField(0));
void* ptr = field->Value();
return static_cast<DrawingMethods*>(ptr);
}
void DrawingMethods::Save(const v8::FunctionCallbackInfo<v8::Value>& args) {
DrawingMethods* drawingMethods = Unwrap(args.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
canvas->save();
}
void DrawingMethods::Restore(const v8::FunctionCallbackInfo<v8::Value>& args) {
DrawingMethods* drawingMethods = Unwrap(args.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
canvas->restore();
}
void DrawingMethods::Rotate(const v8::FunctionCallbackInfo<v8::Value>& args) {
DrawingMethods* drawingMethods = Unwrap(args.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
if (args.Length() != 1) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 1 arguments required."));
return;
}
double angle = args[0]->NumberValue();
canvas->rotate(SkRadiansToDegrees(angle));
}
void DrawingMethods::Translate(const v8::FunctionCallbackInfo<v8::Value>& args) {
DrawingMethods* drawingMethods = Unwrap(args.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
if (args.Length() != 2) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 2 arguments required."));
return;
}
double dx = args[0]->NumberValue();
double dy = args[1]->NumberValue();
canvas->translate(SkDoubleToScalar(dx), SkDoubleToScalar(dy));
}
void DrawingMethods::ResetTransform(const v8::FunctionCallbackInfo<v8::Value>& args) {
DrawingMethods* drawingMethods = Unwrap(args.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
canvas->resetMatrix();
}
void DrawingMethods::DrawPath(const v8::FunctionCallbackInfo<v8::Value>& args) {
DrawingMethods* drawingMethods = Unwrap(args.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
if (args.Length() != 1) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 1 argument required."));
return;
}
v8::Handle<v8::External> field = v8::Handle<v8::External>::Cast(
args[0]->ToObject()->GetInternalField(0));
void* ptr = field->Value();
Path2D* path = static_cast<Path2D*>(ptr);
if (NULL == path) {
return;
}
// TODO(jcgregorio) Add support for Paint2D parameter after Paint2D is
// implemented.
SkPaint fillStyle;
fillStyle.setColor(SK_ColorBLACK);
fillStyle.setAntiAlias(true);
fillStyle.setStyle(SkPaint::kFill_Style);
canvas->drawPath(*(path->path()), fillStyle);
}
void DrawingMethods::GetWidth(v8::Local<v8::String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
DrawingMethods* drawingMethods = Unwrap(info.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
info.GetReturnValue().Set(
v8::Int32::New(
drawingMethods->fGlobal->getIsolate(), canvas->imageInfo().width()));
}
void DrawingMethods::GetHeight(v8::Local<v8::String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {
DrawingMethods* drawingMethods = Unwrap(info.This());
SkCanvas* canvas = drawingMethods->getCanvas();
if (NULL == canvas) {
return;
}
info.GetReturnValue().Set(
v8::Int32::New(
drawingMethods->fGlobal->getIsolate(), canvas->imageInfo().height()));
}
#define ADD_METHOD(name, fn) \
tmpl->Set(v8::String::NewFromUtf8( \
fGlobal->getIsolate(), name, \
v8::String::kInternalizedString), \
v8::FunctionTemplate::New(fGlobal->getIsolate(), fn))
void DrawingMethods::addAttributesAndMethods(v8::Handle<v8::ObjectTemplate> tmpl) {
v8::HandleScope scope(fGlobal->getIsolate());
// Add accessors for each of the fields of the context object.
tmpl->SetAccessor(v8::String::NewFromUtf8(
fGlobal->getIsolate(), "width", v8::String::kInternalizedString),
GetWidth);
tmpl->SetAccessor(v8::String::NewFromUtf8(
fGlobal->getIsolate(), "height", v8::String::kInternalizedString),
GetHeight);
// Add methods.
ADD_METHOD("save", Save);
ADD_METHOD("restore", Restore);
ADD_METHOD("rotate", Rotate);
ADD_METHOD("translate", Translate);
ADD_METHOD("resetTransform", ResetTransform);
ADD_METHOD("drawPath", DrawPath);
}

View File

@ -1,57 +0,0 @@
/*
* Copyright 2014 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef SkV8Example_DrawingMethods_DEFINED
#define SkV8Example_DrawingMethods_DEFINED
#include <v8.h>
class SkCanvas;
class Global;
// DrawingMethods contains common functionality for both Context, Image2Builder,
// and DisplayListBuiler.
class DrawingMethods {
public:
DrawingMethods(Global* global)
: fGlobal(global)
{}
virtual ~DrawingMethods() {}
// Retrieve the SkCanvas to draw on. May return NULL.
virtual SkCanvas* getCanvas() = 0;
// Add the Javascript attributes and methods that DrawingMethods
// implements to the ObjectTemplate.
void addAttributesAndMethods(v8::Handle<v8::ObjectTemplate> tmpl);
protected:
// Get the pointer out of obj.
static DrawingMethods* Unwrap(v8::Handle<v8::Object> obj);
Global* fGlobal;
private:
// JS Attributes
static void GetWidth(v8::Local<v8::String> name,
const v8::PropertyCallbackInfo<v8::Value>& info);
static void GetHeight(v8::Local<v8::String> name,
const v8::PropertyCallbackInfo<v8::Value>& info);
// JS Methods
static void Save(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Restore(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Rotate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Translate(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ResetTransform(const v8::FunctionCallbackInfo<v8::Value>& args);
static void DrawPath(const v8::FunctionCallbackInfo<v8::Value>& args);
};
#endif

View File

@ -1,245 +0,0 @@
/*
* Copyright 2013 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include "Global.h"
#include "SkWindow.h"
#include "SkEvent.h"
Global* Global::gGlobal = NULL;
// Extracts a C string from a V8 Utf8Value.
static const char* to_cstring(const v8::String::Utf8Value& value) {
return *value ? *value : "<string conversion failed>";
}
int32_t Global::getNextTimerID() {
do {
fLastTimerID++;
if (fLastTimerID < 0) {
fLastTimerID = 0;
}
} while (fTimeouts.find(fLastTimerID) != fTimeouts.end());
return fLastTimerID;
}
// Slight modification to an original function found in the V8 sample shell.cc.
void Global::reportException(v8::TryCatch* tryCatch) {
v8::HandleScope handleScope(fIsolate);
v8::String::Utf8Value exception(tryCatch->Exception());
const char* exceptionString = to_cstring(exception);
v8::Handle<v8::Message> message = tryCatch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
fprintf(stderr, "%s\n", exceptionString);
} else {
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
const char* filenameString = to_cstring(filename);
int linenum = message->GetLineNumber();
fprintf(stderr,
"%s:%i: %s\n", filenameString, linenum, exceptionString);
// Print line of source code.
v8::String::Utf8Value sourceline(message->GetSourceLine());
const char* sourceLineString = to_cstring(sourceline);
fprintf(stderr, "%s\n", sourceLineString);
// Print wavy underline.
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
fprintf(stderr, " ");
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
fprintf(stderr, "^");
}
fprintf(stderr, "\n");
v8::String::Utf8Value stackTrace(tryCatch->StackTrace());
if (stackTrace.length() > 0) {
const char* stackTraceString = to_cstring(stackTrace);
fprintf(stderr, "%s\n", stackTraceString);
}
}
}
// The callback that implements the JavaScript 'inval' function.
// Invalidates the current window, forcing a redraw.
//
// JS: inval();
void Global::Inval(const v8::FunctionCallbackInfo<v8::Value>& args) {
gGlobal->getWindow()->inval(NULL);
}
// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called. Prints its arguments on stdout separated by
// spaces and ending with a newline.
//
// JS: print("foo", "bar");
void Global::Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
bool first = true;
v8::HandleScope handleScope(args.GetIsolate());
for (int i = 0; i < args.Length(); i++) {
if (first) {
first = false;
} else {
printf(" ");
}
v8::String::Utf8Value str(args[i]);
printf("%s", to_cstring(str));
}
printf("\n");
fflush(stdout);
}
// The callback that is invoked by v8 whenever the JavaScript 'setTimeout'
// function is called.
//
// JS: setTimeout(on_timeout, 500);
void Global::SetTimeout(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 2) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 2 arguments required."));
return;
}
// Pull out the first arg, make sure it's a function.
if (!args[0]->IsFunction()) {
printf("Not a function passed to setTimeout.\n");
return;
}
v8::Handle<v8::Function> timeoutFn = v8::Handle<v8::Function>::Cast(args[0]);
double delay = args[1]->NumberValue();
int32_t id = gGlobal->getNextTimerID();
gGlobal->fTimeouts[id].Reset(gGlobal->fIsolate, timeoutFn);
// Create an SkEvent and add it with the right delay.
SkEvent* evt = new SkEvent();
evt->setTargetProc(Global::TimeOutProc);
evt->setFast32(id);
evt->postDelay(delay);
args.GetReturnValue().Set(v8::Integer::New(gGlobal->fIsolate, id));
}
// Callback function for SkEvents used to implement timeouts.
bool Global::TimeOutProc(const SkEvent& evt) {
// Create a handle scope to keep the temporary object references.
v8::HandleScope handleScope(gGlobal->getIsolate());
// Create a local context from our global context.
v8::Local<v8::Context> context = gGlobal->getContext();
// Enter the context so all the remaining operations take place there.
v8::Context::Scope contextScope(context);
// Set up an exception handler before calling the Process function.
v8::TryCatch tryCatch;
int32_t id = evt.getFast32();
if (gGlobal->fTimeouts.find(gGlobal->fLastTimerID) == gGlobal->fTimeouts.end()) {
printf("Not a valid timer ID.\n");
return true;
}
const int argc = 0;
v8::Local<v8::Function> onTimeout =
v8::Local<v8::Function>::New(gGlobal->getIsolate(), gGlobal->fTimeouts[id]);
v8::Handle<v8::Value> result = onTimeout->Call(context->Global(), argc, NULL);
gGlobal->fTimeouts.erase(id);
// Handle any exceptions or output.
if (result.IsEmpty()) {
SkASSERT(tryCatch.HasCaught());
// Print errors that happened during execution.
gGlobal->reportException(&tryCatch);
} else {
SkASSERT(!tryCatch.HasCaught());
if (!result->IsUndefined()) {
// If all went well and the result wasn't undefined then print the
// returned value.
v8::String::Utf8Value str(result);
const char* cstr = to_cstring(str);
printf("%s\n", cstr);
}
}
return true;
}
// Creates a new execution environment containing the built-in functions.
v8::Handle<v8::Context> Global::createRootContext() {
// Create a template for the global object.
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
global->Set(v8::String::NewFromUtf8(fIsolate, "print"),
v8::FunctionTemplate::New(fIsolate, Global::Print));
global->Set(v8::String::NewFromUtf8(fIsolate, "setTimeout"),
v8::FunctionTemplate::New(fIsolate, Global::SetTimeout));
global->Set(v8::String::NewFromUtf8(fIsolate, "inval"),
v8::FunctionTemplate::New(fIsolate, Global::Inval));
return v8::Context::New(fIsolate, NULL, global);
}
void Global::initialize() {
// Create a stack-allocated handle scope.
v8::HandleScope handleScope(fIsolate);
// Create a new context.
v8::Handle<v8::Context> context = this->createRootContext();
// Make the context persistent.
fContext.Reset(fIsolate, context);
}
// Creates the root context, parses the script into it, then stores the
// context in a global.
//
// TODO(jcgregorio) Currently only handles one script. Need to move
// createRootContext to another call that's only done once.
bool Global::parseScript(const char script[]) {
// Create a stack-allocated handle scope.
v8::HandleScope handleScope(fIsolate);
// Get the global context.
v8::Handle<v8::Context> context = this->getContext();
// Enter the scope so all operations take place in the scope.
v8::Context::Scope contextScope(context);
v8::TryCatch tryCatch;
// Compile the source code.
v8::Handle<v8::String> source = v8::String::NewFromUtf8(fIsolate, script);
v8::Handle<v8::Script> compiledScript = v8::Script::Compile(source);
if (compiledScript.IsEmpty()) {
// Print errors that happened during compilation.
this->reportException(&tryCatch);
return false;
}
// Try running it now to create the onDraw function.
v8::Handle<v8::Value> result = compiledScript->Run();
// Handle any exceptions or output.
if (result.IsEmpty()) {
SkASSERT(tryCatch.HasCaught());
// Print errors that happened during execution.
this->reportException(&tryCatch);
return false;
}
return true;
}

View File

@ -1,84 +0,0 @@
/*
* Copyright 2013 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef SkV8Example_Global_DEFINED
#define SkV8Example_Global_DEFINED
#include <map>
#include <v8.h>
#include "SkTypes.h"
#include "SkEvent.h"
class SkOSWindow;
typedef v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function> > CopyablePersistentFn;
// Provides the global isolate and context for our V8 instance.
// Also implements all the global level functions.
class Global : SkNoncopyable {
public:
Global(v8::Isolate* isolate)
: fIsolate(isolate)
, fWindow(NULL)
, fLastTimerID(0)
{
gGlobal = this;
this->initialize();
}
virtual ~Global() {}
// The script will be parsed into the context this Global contains.
bool parseScript(const char script[]);
v8::Local<v8::Context> getContext() {
return v8::Local<v8::Context>::New(fIsolate, fContext);
}
v8::Isolate* getIsolate() {
return fIsolate;
}
void setWindow(SkOSWindow* win) {
fWindow = win;
}
SkOSWindow* getWindow() {
return fWindow;
}
void reportException(v8::TryCatch* tryCatch);
private:
void initialize();
v8::Handle<v8::Context> createRootContext();
int32_t getNextTimerID();
static bool TimeOutProc(const SkEvent& evt);
// Static functions that implement the global JS functions we add to
// the context.
static void SetTimeout(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Print(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Inval(const v8::FunctionCallbackInfo<v8::Value>& args);
v8::Persistent<v8::Context> fContext;
v8::Isolate* fIsolate;
SkOSWindow* fWindow;
static Global* gGlobal;
// Handle to the functions to call when a timeout triggers as indexed by id.
std::map<int32_t, CopyablePersistentFn > fTimeouts;
// Last timer ID generated.
int32_t fLastTimerID;
};
#endif

View File

@ -1,138 +0,0 @@
/*
* Copyright 2013 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <v8.h>
#include "Global.h"
#include "JsContext.h"
#include "Path2D.h"
#include "SkCanvas.h"
// Extracts a C string from a V8 Utf8Value.
// TODO(jcgregrio) Currently dup'd in two files, fix.
static const char* to_cstring(const v8::String::Utf8Value& value) {
return *value ? *value : "<string conversion failed>";
}
v8::Persistent<v8::ObjectTemplate> JsContext::gContextTemplate;
// Wraps 'this' in a Javascript object.
v8::Handle<v8::Object> JsContext::wrap() {
// Handle scope for temporary handles.
v8::EscapableHandleScope handleScope(fGlobal->getIsolate());
// Fetch the template for creating JavaScript JsContext wrappers.
// It only has to be created once, which we do on demand.
if (gContextTemplate.IsEmpty()) {
v8::Local<v8::ObjectTemplate> localTemplate = v8::ObjectTemplate::New();
// Add a field to store the pointer to a JsContext instance.
localTemplate->SetInternalFieldCount(1);
this->addAttributesAndMethods(localTemplate);
gContextTemplate.Reset(fGlobal->getIsolate(), localTemplate);
}
v8::Handle<v8::ObjectTemplate> templ =
v8::Local<v8::ObjectTemplate>::New(fGlobal->getIsolate(), gContextTemplate);
// Create an empty JsContext wrapper.
v8::Local<v8::Object> result = templ->NewInstance();
// Wrap the raw C++ pointer in an External so it can be referenced
// from within JavaScript.
v8::Handle<v8::External> contextPtr = v8::External::New(fGlobal->getIsolate(), this);
// Store the context pointer in the JavaScript wrapper.
result->SetInternalField(0, contextPtr);
// Return the result through the current handle scope. Since each
// of these handles will go away when the handle scope is deleted
// we need to call Close to let one, the result, escape into the
// outer handle scope.
return handleScope.Escape(result);
}
void JsContext::onDraw(SkCanvas* canvas) {
// Record canvas and window in this.
fCanvas = canvas;
// Create a handle scope to keep the temporary object references.
v8::HandleScope handleScope(fGlobal->getIsolate());
// Create a local context from our global context.
v8::Local<v8::Context> context = fGlobal->getContext();
// Enter the context so all the remaining operations take place there.
v8::Context::Scope contextScope(context);
// Wrap the C++ this pointer in a JavaScript wrapper.
v8::Handle<v8::Object> contextObj = this->wrap();
// Set up an exception handler before calling the Process function.
v8::TryCatch tryCatch;
// Invoke the process function, giving the global object as 'this'
// and one argument, this JsContext.
const int argc = 1;
v8::Handle<v8::Value> argv[argc] = { contextObj };
v8::Local<v8::Function> onDraw =
v8::Local<v8::Function>::New(fGlobal->getIsolate(), fOnDraw);
v8::Handle<v8::Value> result = onDraw->Call(context->Global(), argc, argv);
// Handle any exceptions or output.
if (result.IsEmpty()) {
SkASSERT(tryCatch.HasCaught());
// Print errors that happened during execution.
fGlobal->reportException(&tryCatch);
} else {
SkASSERT(!tryCatch.HasCaught());
if (!result->IsUndefined()) {
// If all went well and the result wasn't undefined then print
// the returned value.
v8::String::Utf8Value str(result);
const char* cstr = to_cstring(str);
printf("%s\n", cstr);
}
}
}
// Fetch the onDraw function from the global context.
bool JsContext::initialize() {
// Create a stack-allocated handle scope.
v8::HandleScope handleScope(fGlobal->getIsolate());
// Create a local context from our global context.
v8::Local<v8::Context> context = fGlobal->getContext();
// Enter the scope so all operations take place in the scope.
v8::Context::Scope contextScope(context);
v8::TryCatch try_catch;
v8::Handle<v8::String> fn_name = v8::String::NewFromUtf8(
fGlobal->getIsolate(), "onDraw");
v8::Handle<v8::Value> fn_val = context->Global()->Get(fn_name);
if (!fn_val->IsFunction()) {
printf("Not a function.\n");
return false;
}
// It is a function; cast it to a Function.
v8::Handle<v8::Function> fn_fun = v8::Handle<v8::Function>::Cast(fn_val);
// Store the function in a Persistent handle, since we also want that to
// remain after this call returns.
fOnDraw.Reset(fGlobal->getIsolate(), fn_fun);
return true;
}

View File

@ -1,63 +0,0 @@
/*
* Copyright 2014 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef SkV8Example_JsContext_DEFINED
#define SkV8Example_JsContext_DEFINED
#include <v8.h>
#include "SkPaint.h"
#include "DrawingMethods.h"
class SkCanvas;
class Global;
// Provides the canvas context implementation in JS, and the OnDraw() method in
// C++ that's used to bridge from C++ to JS. Should be used in JS as:
//
// function onDraw(context) {
// context.fillStyle="#FF0000";
// context.fillRect(x, y, w, h);
// }
class JsContext : public DrawingMethods {
public:
JsContext(Global* global)
: INHERITED(global)
, fCanvas(NULL)
{
}
virtual ~JsContext() {}
// Parse the script.
bool initialize();
// Call this with the SkCanvas you want onDraw to draw on.
void onDraw(SkCanvas* canvas);
virtual SkCanvas* getCanvas() { return fCanvas; };
private:
// Wrap the 'this' pointer into an Object. Can be retrieved via Unwrap.
v8::Handle<v8::Object> wrap();
// A handle to the onDraw function defined in the script.
v8::Persistent<v8::Function> fOnDraw;
// The template for what a canvas context object looks like. The canvas
// context object is what's passed into the JS onDraw() function.
static v8::Persistent<v8::ObjectTemplate> gContextTemplate;
// Only valid when inside OnDraw().
SkCanvas* fCanvas;
typedef DrawingMethods INHERITED;
};
#endif

View File

@ -1,55 +0,0 @@
/*
* Copyright 2014 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include "Path2D.h"
#include "Global.h"
Global* Path2D::gGlobal = NULL;
v8::Persistent<v8::ObjectTemplate> Path2D::gPath2DTemplate;
void weakPath2DCallback(const v8::WeakCallbackData<v8::Object, Path2D>& args) {
delete args.GetParameter();
}
// Wraps an SkPath* in a Path2D object.
Path2D::Path2D(SkPath* path) : path_(path) {
// Handle scope for temporary handles.
v8::HandleScope handleScope(gGlobal->getIsolate());
// Just once create the ObjectTemplate for what Path2D looks like in JS.
if (gPath2DTemplate.IsEmpty()) {
v8::Local<v8::ObjectTemplate> localTemplate = v8::ObjectTemplate::New();
// Add a field to store the pointer to a SkPath pointer.
localTemplate->SetInternalFieldCount(1);
gPath2DTemplate.Reset(gGlobal->getIsolate(), localTemplate);
}
v8::Handle<v8::ObjectTemplate> templ =
v8::Local<v8::ObjectTemplate>::New(gGlobal->getIsolate(), gPath2DTemplate);
// Create an empty Path2D wrapper.
v8::Local<v8::Object> result = templ->NewInstance();
// Store the SkPath pointer in the JavaScript wrapper.
result->SetInternalField(0, v8::External::New(gGlobal->getIsolate(), this));
gGlobal->getIsolate()->AdjustAmountOfExternalAllocatedMemory(sizeof(SkPath));
// Make a weak persistent and set up the callback so we can delete the path pointer.
// TODO(jcgregorio) Figure out why weakPath2DCallback never gets called and we leak.
v8::Persistent<v8::Object> weak(gGlobal->getIsolate(), result);
weak.SetWeak(this, weakPath2DCallback);
this->handle_.Reset(gGlobal->getIsolate(), weak);
}
Path2D::~Path2D() {
delete path_;
handle_.Reset();
gGlobal->getIsolate()->AdjustAmountOfExternalAllocatedMemory(-sizeof(SkPath));
}

View File

@ -1,51 +0,0 @@
/*
* Copyright 2014 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef SkV8Example_Path2D_DEFINED
#define SkV8Example_Path2D_DEFINED
#include <v8.h>
#include "SkPath.h"
#include "SkTypes.h"
class Global;
// Path2D bridges between JS and SkPath.
class Path2D : SkNoncopyable {
public:
Path2D(SkPath* path);
virtual ~Path2D();
static void AddToGlobal(Global* global) {
gGlobal = global;
}
v8::Persistent<v8::Object>& persistent() {
return handle_;
}
SkPath* path() {
return path_;
}
private:
// The handle to this object in JS space.
v8::Persistent<v8::Object> handle_;
SkPath* path_;
// The global context we are running in.
static Global* gGlobal;
// The template for what a JS Path2D object looks like.
static v8::Persistent<v8::ObjectTemplate> gPath2DTemplate;
};
#endif

View File

@ -1,261 +0,0 @@
/*
* Copyright 2014 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include "Global.h"
#include "Path2DBuilder.h"
#include "Path2D.h"
#include "SkPath.h"
Global* Path2DBuilder::gGlobal = NULL;
void Path2DBuilder::ConstructPath(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope handleScope(gGlobal->getIsolate());
Path2DBuilder* path = new Path2DBuilder();
args.This()->SetInternalField(
0, v8::External::New(gGlobal->getIsolate(), path));
}
#define ADD_METHOD(name, fn) \
constructor->InstanceTemplate()->Set( \
v8::String::NewFromUtf8( \
global->getIsolate(), name, \
v8::String::kInternalizedString), \
v8::FunctionTemplate::New(global->getIsolate(), fn))
// Install the constructor in the global scope so Path2DBuilders can be constructed
// in JS.
void Path2DBuilder::AddToGlobal(Global* global) {
gGlobal = global;
// Create a stack-allocated handle scope.
v8::HandleScope handleScope(gGlobal->getIsolate());
v8::Handle<v8::Context> context = gGlobal->getContext();
// Enter the scope so all operations take place in the scope.
v8::Context::Scope contextScope(context);
v8::Local<v8::FunctionTemplate> constructor = v8::FunctionTemplate::New(
gGlobal->getIsolate(), Path2DBuilder::ConstructPath);
constructor->InstanceTemplate()->SetInternalFieldCount(1);
ADD_METHOD("close", ClosePath);
ADD_METHOD("moveTo", MoveTo);
ADD_METHOD("lineTo", LineTo);
ADD_METHOD("quadraticCurveTo", QuadraticCurveTo);
ADD_METHOD("bezierCurveTo", BezierCurveTo);
ADD_METHOD("arc", Arc);
ADD_METHOD("rect", Rect);
ADD_METHOD("oval", Oval);
ADD_METHOD("conicTo", ConicTo);
ADD_METHOD("finalize", Finalize);
context->Global()->Set(v8::String::NewFromUtf8(
gGlobal->getIsolate(), "Path2DBuilder"), constructor->GetFunction());
}
Path2DBuilder* Path2DBuilder::Unwrap(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Handle<v8::External> field = v8::Handle<v8::External>::Cast(
args.This()->GetInternalField(0));
void* ptr = field->Value();
return static_cast<Path2DBuilder*>(ptr);
}
void Path2DBuilder::ClosePath(const v8::FunctionCallbackInfo<v8::Value>& args) {
Path2DBuilder* path = Unwrap(args);
path->fSkPath.close();
}
void Path2DBuilder::MoveTo(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 2) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 2 arguments required."));
return;
}
double x = args[0]->NumberValue();
double y = args[1]->NumberValue();
Path2DBuilder* path = Unwrap(args);
path->fSkPath.moveTo(SkDoubleToScalar(x), SkDoubleToScalar(y));
}
void Path2DBuilder::LineTo(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 2) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 2 arguments required."));
return;
}
double x = args[0]->NumberValue();
double y = args[1]->NumberValue();
Path2DBuilder* path = Unwrap(args);
path->fSkPath.lineTo(SkDoubleToScalar(x), SkDoubleToScalar(y));
}
void Path2DBuilder::QuadraticCurveTo(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 4) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 4 arguments required."));
return;
}
double cpx = args[0]->NumberValue();
double cpy = args[1]->NumberValue();
double x = args[2]->NumberValue();
double y = args[3]->NumberValue();
Path2DBuilder* path = Unwrap(args);
// TODO(jcgregorio) Doesn't handle the empty last path case correctly per
// the HTML 5 spec.
path->fSkPath.quadTo(
SkDoubleToScalar(cpx), SkDoubleToScalar(cpy),
SkDoubleToScalar(x), SkDoubleToScalar(y));
}
void Path2DBuilder::BezierCurveTo(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 6) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 6 arguments required."));
return;
}
double cp1x = args[0]->NumberValue();
double cp1y = args[1]->NumberValue();
double cp2x = args[2]->NumberValue();
double cp2y = args[3]->NumberValue();
double x = args[4]->NumberValue();
double y = args[5]->NumberValue();
Path2DBuilder* path = Unwrap(args);
// TODO(jcgregorio) Doesn't handle the empty last path case correctly per
// the HTML 5 spec.
path->fSkPath.cubicTo(
SkDoubleToScalar(cp1x), SkDoubleToScalar(cp1y),
SkDoubleToScalar(cp2x), SkDoubleToScalar(cp2y),
SkDoubleToScalar(x), SkDoubleToScalar(y));
}
void Path2DBuilder::Arc(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 5 && args.Length() != 6) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 5 or 6 args required."));
return;
}
double x = args[0]->NumberValue();
double y = args[1]->NumberValue();
double radius = args[2]->NumberValue();
double startAngle = args[3]->NumberValue();
double endAngle = args[4]->NumberValue();
bool antiClockwise = false;
if (args.Length() == 6) {
antiClockwise = args[5]->BooleanValue();
}
double sweepAngle;
if (!antiClockwise) {
sweepAngle = endAngle - startAngle;
} else {
sweepAngle = startAngle - endAngle;
startAngle = endAngle;
}
Path2DBuilder* path = Unwrap(args);
SkRect rect = {
SkDoubleToScalar(x-radius),
SkDoubleToScalar(y-radius),
SkDoubleToScalar(x+radius),
SkDoubleToScalar(y+radius)
};
path->fSkPath.addArc(rect, SkRadiansToDegrees(startAngle),
SkRadiansToDegrees(sweepAngle));
}
void Path2DBuilder::Rect(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 4) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 4 arguments required."));
return;
}
double x = args[0]->NumberValue();
double y = args[1]->NumberValue();
double w = args[2]->NumberValue();
double h = args[3]->NumberValue();
SkRect rect = {
SkDoubleToScalar(x),
SkDoubleToScalar(y),
SkDoubleToScalar(x) + SkDoubleToScalar(w),
SkDoubleToScalar(y) + SkDoubleToScalar(h)
};
Path2DBuilder* path = Unwrap(args);
path->fSkPath.addRect(rect);
}
void Path2DBuilder::Oval(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 4 && args.Length() != 5) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 4 or 5 args required."));
return;
}
double x = args[0]->NumberValue();
double y = args[1]->NumberValue();
double radiusX = args[2]->NumberValue();
double radiusY = args[3]->NumberValue();
SkPath::Direction dir = SkPath::kCW_Direction;
if (args.Length() == 5 && !args[4]->BooleanValue()) {
dir = SkPath::kCCW_Direction;
}
Path2DBuilder* path = Unwrap(args);
SkRect rect = {
SkDoubleToScalar(x-radiusX),
SkDoubleToScalar(y-radiusX),
SkDoubleToScalar(x+radiusY),
SkDoubleToScalar(y+radiusY)
};
path->fSkPath.addOval(rect, dir);
}
void Path2DBuilder::ConicTo(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 5) {
args.GetIsolate()->ThrowException(
v8::String::NewFromUtf8(
args.GetIsolate(), "Error: 5 args required."));
return;
}
double x1 = args[0]->NumberValue();
double y1 = args[1]->NumberValue();
double x2 = args[2]->NumberValue();
double y2 = args[3]->NumberValue();
double w = args[4]->NumberValue();
Path2DBuilder* path = Unwrap(args);
path->fSkPath.conicTo(
SkDoubleToScalar(x1),
SkDoubleToScalar(y1),
SkDoubleToScalar(x2),
SkDoubleToScalar(y2),
SkDoubleToScalar(w)
);
}
void Path2DBuilder::Finalize(const v8::FunctionCallbackInfo<v8::Value>& args) {
Path2DBuilder* path = Unwrap(args);
// Build Path2D from out fSkPath and return it.
SkPath* skPath = new SkPath(path->fSkPath);
path->fSkPath.reset();
Path2D* pathWrap = new Path2D(skPath);
args.GetReturnValue().Set(pathWrap->persistent());
}

View File

@ -1,53 +0,0 @@
/*
* Copyright 2014 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef SkV8Example_Path2DBuilder_DEFINED
#define SkV8Example_Path2DBuilder_DEFINED
#include <v8.h>
#include "SkPath.h"
#include "SkTypes.h"
class Global;
class Path2DBuilder : SkNoncopyable {
public:
Path2DBuilder() : fSkPath() {}
virtual ~Path2DBuilder() {}
const SkPath& getSkPath() { return fSkPath; }
// The JS Path2DBuilder constuctor implementation.
static void ConstructPath(const v8::FunctionCallbackInfo<v8::Value>& args);
// Add the Path2DBuilder JS constructor to the global context.
static void AddToGlobal(Global* global);
// Path2DBuilder JS methods.
static void ClosePath(const v8::FunctionCallbackInfo<v8::Value>& args);
static void MoveTo(const v8::FunctionCallbackInfo<v8::Value>& args);
static void LineTo(const v8::FunctionCallbackInfo<v8::Value>& args);
static void QuadraticCurveTo(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void BezierCurveTo(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Arc(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Rect(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Oval(const v8::FunctionCallbackInfo<v8::Value>& args);
static void ConicTo(const v8::FunctionCallbackInfo<v8::Value>& args);
static void Finalize(const v8::FunctionCallbackInfo<v8::Value>& args);
private:
SkPath fSkPath;
static Path2DBuilder* Unwrap(const v8::FunctionCallbackInfo<v8::Value>& args);
static Global* gGlobal;
};
#endif

View File

@ -1,16 +0,0 @@
Build Instructions
==================
V8 gyp is not quite standard and Chromium uses a Python script
to work around that, for now we have some manual steps to do
before you can compile and run this sample:
1. Uncomment out the v8 dep in DEPS and re-run gclient sync.
2. Run 'make dependencies' in third_pary/externals/v8.
3. Run 'make native' in third_pary/externals/v8.
4. Uncomment SkV8Example in gyp/everything.gyp.
5. Run 'ninja -C out/Debug SkV8Example'
6. Run the sample as:
./out/Debug/SkV8Example --infile experimental/SkV8Example/js/speed.js

View File

@ -1,227 +0,0 @@
/*
* Copyright 2013 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <v8.h>
#include <include/libplatform/libplatform.h>
#include "SkV8Example.h"
#include "Global.h"
#include "JsContext.h"
#include "Path2D.h"
#include "Path2DBuilder.h"
#include "GrBackendSurface.h"
#include "gl/GrGLUtil.h"
#include "gl/GrGLDefines.h"
#include "gl/GrGLInterface.h"
#include "GrContext.h"
#include "SkApplication.h"
#include "SkCommandLineFlags.h"
#include "SkData.h"
#include "SkDraw.h"
#include "SkGpuDevice.h"
#include "SkGraphics.h"
#include "SkScalar.h"
#include "SkSurface.h"
DEFINE_string2(infile, i, NULL, "Name of file to load JS from.\n");
DEFINE_bool(gpu, true, "Use the GPU for rendering.");
void application_init() {
SkGraphics::Init();
SkEvent::Init();
}
void application_term() {
SkEvent::Term();
}
SkV8ExampleWindow::SkV8ExampleWindow(void* hwnd, JsContext* context)
: INHERITED(hwnd)
, fJsContext(context)
#if SK_SUPPORT_GPU
, fCurContext(NULL)
, fCurIntf(NULL)
, fCurSurface(NULL)
#endif
{
this->setVisibleP(true);
this->setClipToBounds(false);
#if SK_SUPPORT_GPU
this->windowSizeChanged();
#endif
}
SkV8ExampleWindow::~SkV8ExampleWindow() {
#if SK_SUPPORT_GPU
SkSafeUnref(fCurContext);
SkSafeUnref(fCurIntf);
SkSafeUnref(fCurSurface);
#endif
}
#if SK_SUPPORT_GPU
void SkV8ExampleWindow::windowSizeChanged() {
if (FLAGS_gpu) {
SkOSWindow::AttachmentInfo attachmentInfo;
bool result = this->attach(
SkOSWindow::kNativeGL_BackEndType, 0, false, &attachmentInfo);
if (!result) {
printf("Failed to attach.");
exit(1);
}
fCurIntf = GrGLCreateNativeInterface();
fCurContext = GrContext::MakeGL(fCurIntf).release();
if (NULL == fCurIntf || NULL == fCurContext) {
printf("Failed to initialize GL.");
exit(1);
}
GrGLFramebufferInfo framebufferInfo;
GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &framebufferInfo.fFBOID);
GrBackendRenderTarget backendRenderTarget(SkScalarRoundToInt(this->width()),
SkScalarRoundToInt(this->height()),
attachmentInfo.fSampleCount,
attachmentInfo.fStencilBits,
kSkia8888_GrPixelConfig,
framebufferInfo);
SkSafeUnref(fCurSurface);
fCurSurface = SkSurface::MakeFromBackendRenderTarget(fCurContext, backendRenderTarget,
kBottomLeft_GrSurfaceOrigin,
nullptr, nullptr).release();
}
}
#endif
#if SK_SUPPORT_GPU
SkSurface* SkV8ExampleWindow::createSurface() {
if (FLAGS_gpu) {
// Increase the ref count since callers of createSurface put the
// results in a sk_sp.
fCurSurface->ref();
return fCurSurface;
} else {
return this->INHERITED::createSurface();
}
}
#endif
void SkV8ExampleWindow::onSizeChange() {
this->INHERITED::onSizeChange();
#if SK_SUPPORT_GPU
this->windowSizeChanged();
#endif
}
Global* global = NULL;
std::unique_ptr<v8::Platform> platform;
void SkV8ExampleWindow::onDraw(SkCanvas* canvas) {
canvas->save();
canvas->drawColor(SK_ColorWHITE);
// Now jump into JS and call the onDraw(canvas) method defined there.
fJsContext->onDraw(canvas);
canvas->restore();
this->INHERITED::onDraw(canvas);
#if SK_SUPPORT_GPU
if (FLAGS_gpu) {
fCurContext->flush();
this->present();
}
#endif
}
#ifdef SK_BUILD_FOR_WIN
void SkV8ExampleWindow::onHandleInval(const SkIRect& rect) {
RECT winRect;
winRect.top = rect.top();
winRect.bottom = rect.bottom();
winRect.right = rect.right();
winRect.left = rect.left();
InvalidateRect((HWND)this->getHWND(), &winRect, false);
}
#endif
SkOSWindow* create_sk_window(void* hwnd, int argc, char** argv) {
printf("Started\n");
v8::V8::SetFlagsFromCommandLine(&argc, argv, true);
SkCommandLineFlags::Parse(argc, argv);
v8::V8::InitializeICU();
platform = std::unique_ptr<v8::Platform>(v8::platform::CreateDefaultPlatform());
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
v8::Isolate* isolate = v8::Isolate::New();
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
isolate->Enter();
global = new Global(isolate);
// Set up things to look like a browser by creating
// a console object that invokes our print function.
const char* startupScript =
"function Console() {}; \n"
"Console.prototype.log = function() { \n"
" var args = Array.prototype.slice.call(arguments).join(' '); \n"
" print(args); \n"
"}; \n"
"console = new Console(); \n";
if (!global->parseScript(startupScript)) {
printf("Failed to parse startup script: %s.\n", FLAGS_infile[0]);
exit(1);
}
const char* script =
"function onDraw(canvas) { \n"
" canvas.fillStyle = '#00FF00'; \n"
" canvas.fillRect(20, 20, 100, 100); \n"
" canvas.inval(); \n"
"} \n";
sk_sp<SkData> data;
if (FLAGS_infile.count()) {
data = SkData::MakeFromFileName(FLAGS_infile[0]);
script = static_cast<const char*>(data->data());
}
if (NULL == script) {
printf("Could not load file: %s.\n", FLAGS_infile[0]);
exit(1);
}
Path2DBuilder::AddToGlobal(global);
Path2D::AddToGlobal(global);
if (!global->parseScript(script)) {
printf("Failed to parse file: %s.\n", FLAGS_infile[0]);
exit(1);
}
JsContext* jsContext = new JsContext(global);
if (!jsContext->initialize()) {
printf("Failed to initialize.\n");
exit(1);
}
SkV8ExampleWindow* win = new SkV8ExampleWindow(hwnd, jsContext);
global->setWindow(win);
return win;
}

View File

@ -1,53 +0,0 @@
/*
* Copyright 2013 Google Inc.
*
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef SkV8Example_DEFINED
#define SkV8Example_DEFINED
#include "SkWindow.h"
class GrContext;
class GrGLInterface;
class GrRenderTarget;
class SkSurface;
class JsContext;
class SkV8ExampleWindow : public SkOSWindow {
public:
SkV8ExampleWindow(void* hwnd, JsContext* canvas);
virtual ~SkV8ExampleWindow();
protected:
void onDraw(SkCanvas* canvas) override;
void onSizeChange() override;
#if SK_SUPPORT_GPU
SkSurface* createSurface() override;
#endif
#ifdef SK_BUILD_FOR_WIN
void onHandleInval(const SkIRect&) override;
#endif
void windowSizeChanged();
private:
typedef SkOSWindow INHERITED;
JsContext* fJsContext;
#if SK_SUPPORT_GPU
GrContext* fCurContext;
const GrGLInterface* fCurIntf;
GrRenderTarget* fCurRenderTarget;
SkSurface* fCurSurface;
#endif
};
#endif

View File

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Gears</title>
<meta charset="utf-8" />
</head>
<body>
<canvas id=gears width=500 height=500>
<script src="../js/gears.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

View File

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Snow</title>
<meta charset="utf-8" />
</head>
<body>
<canvas id=snow width=500 height=500>
<script src="../js/snow.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

View File

@ -1,183 +0,0 @@
var IS_SKV8 = typeof document == "undefined";
var HAS_PATH = typeof Path2D != "undefined";
var HAS_DISPLAY_LIST = typeof DisplayList != "undefined";
var NumTeeth = 24;
var NumGears = 60;
var DeltaTheta = Math.PI/90;
var FaceColors = ["#000099", "#006600", "#990000", "#EEEE00"];
var SideColors = ["#0000FF", "#009900", "#FF0000", "#CCCC00"];
function makeGear(pathLike, r) {
var dT = Math.PI*2/NumTeeth;
var dTq = dT/4;
var outer = r;
var inner = 0.7 * r;
pathLike.moveTo(Math.sin(-2*dTq)*outer, Math.cos(-2*dTq)*outer);
for (var i=0; i<NumTeeth; i+=2) {
pathLike.lineTo(Math.sin(dT*i-dTq)*outer, Math.cos(dT*i-dTq)*outer);
pathLike.lineTo(Math.sin(dT*i+dTq)*inner, Math.cos(dT*i+dTq)*inner);
pathLike.lineTo(Math.sin(dT*(i+1)-dTq)*inner, Math.cos(dT*(i+1)-dTq)*inner);
pathLike.lineTo(Math.sin(dT*(i+1)+dTq)*outer, Math.cos(dT*(i+1)+dTq)*outer);
}
}
function gearPath(r) {
if (HAS_PATH) {
p = new Path2D();
makeGear(p, r)
p.closePath();
return p;
} else {
return null;
}
}
function gearDisplayListStroke(r, color) {
if (HAS_DISPLAY_LIST) {
p = new Path2D();
makeGear(p, r)
p.closePath();
var dl = new DisplayList();
dl.strokeStyle = color;
dl.stroke(p);
dl.finalize()
return dl;
} else {
return null;
}
}
function gearDisplayListFill(r, color) {
if (HAS_DISPLAY_LIST) {
p = new Path2D();
makeGear(p, r)
p.closePath();
var dl = new DisplayList();
dl.fillStyle = color;
dl.fill(p);
dl.finalize()
return dl;
} else {
return null;
}
}
function strokeGear(ctx, gear) {
if (HAS_PATH) {
ctx.stroke(gear.path);
} else {
ctx.beginPath();
makeGear(ctx, gear.r);
ctx.closePath();
ctx.stroke();
}
}
function fillGear(ctx) {
if (HAS_PATH) {
ctx.fill(gear.path);
} else {
ctx.beginPath();
makeGear(ctx, gear.r);
ctx.closePath();
ctx.fill();
}
}
function draw3DGear(ctx, angle, gear) {
ctx.strokeStyle = gear.sideColor;
ctx.fillStyle = gear.faceColor;
ctx.rotate(angle);
strokeGear(ctx, gear);
for (var i=0; i < 20; i++) {
ctx.rotate(-angle);
ctx.translate(0.707, 0.707);
ctx.rotate(angle);
if (HAS_DISPLAY_LIST) {
ctx.draw(gear.gearStroke);
} else {
strokeGear(ctx, gear);
}
}
if (HAS_DISPLAY_LIST) {
ctx.draw(gear.gearFill);
} else {
fillGear(ctx, gear);
}
ctx.rotate(-angle);
}
function draw3DGearAt(ctx, angle, gear) {
ctx.save();
ctx.translate(gear.x, gear.y);
draw3DGear(ctx, angle, gear);
ctx.restore();
}
var onDraw = function() {
var ticks=0;
var rotation = 0;
var gears = [];
for (var i=0; i<NumGears; i++) {
color = Math.floor(Math.random()*FaceColors.length);
r = Math.random()*100+5;
gears.push({
x: Math.random()*500,
y: Math.random()*500,
path: gearPath(r),
gearFill: gearDisplayListFill(r, FaceColors[color]),
gearStroke: gearDisplayListStroke(r, SideColors[color]),
r: r,
faceColor: FaceColors[color],
sideColor: SideColors[color]
});
}
function draw(ctx) {
ctx.resetTransform();
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, 499, 499);
rotation += DeltaTheta;
if (rotation >= Math.PI*2) {
rotation = 0;
}
for (var i=0; i < gears.length; i++) {
gear = gears[i];
draw3DGearAt(ctx, rotation, gear);
}
ticks++;
if (IS_SKV8) {
inval();
}
};
function fps() {
console.log(ticks);
ticks = 0;
setTimeout(fps, 1000);
};
setTimeout(fps, 1000);
return draw;
}();
if (!IS_SKV8) {
window.onload = function(){
var canvas = document.getElementById("gears");
var ctx = canvas.getContext("2d");
function drawCallback() {
onDraw(ctx);
setTimeout(drawCallback, 1);
}
setTimeout(drawCallback, 1);
}
}
console.log("HAS_PATH: " + HAS_PATH);

View File

@ -1,33 +0,0 @@
/**
* @fileoverview Sample onDraw script for use with SkV8Example.
*/
var onDraw = function(){
var p = new Path2D();
p.moveTo(0, 0);
p.bezierCurveTo(0, 100, 100, 0, 200, 200);
p.close();
p.moveTo(0, 300);
p.arc(0, 300, 40, Math.PI/2, 3/2*Math.PI);
function f(context) {
context.translate(10, 10);
for (var i=0; i<256; i++) {
context.strokeStyle = '#0000' + toHex(i);
context.stroke(p);
context.translate(1, 0);
}
context.fillStyle = '#ff0000';
print(context.width, context.height);
context.resetTransform();
context.fillRect(context.width/2, context.height/2, 20, 20);
};
return f;
}();
function toHex(n) {
var s = n.toString(16);
if (s.length == 1) {
s = "0" + s;
}
return s;
}

View File

@ -1,29 +0,0 @@
/**
* @fileoverview Sample onDraw script for use with SkV8Example.
*/
var onDraw = function(){
var ticks = 0;
var b = new Path2DBuilder();
b.rect(0, 0, 200, 200);
var p = b.finalize();
function f(context) {
ticks += 1;
context.translate(context.width/2, context.height/2);
context.rotate(ticks/10);
context.drawPath(p);
inval();
};
function onTimeout() {
console.log(ticks);
ticks = 0;
setTimeout(onTimeout, 1000);
}
setTimeout(onTimeout, 1000);
return f;
}();

View File

@ -1,95 +0,0 @@
var IS_SKV8 = typeof document == "undefined";
var HAS_PATH = typeof Path2D != "undefined";
function circlePath(r) {
if (HAS_PATH) {
var p = new Path2D();
p.arc(0, 0, r, 0, 2*Math.PI);
p.closePath();
return p;
} else {
return null;
}
}
var onDraw = function() {
var W = 500;
var H = 500;
var NumParticles = 100;
var angle = 0;
var ticks = 0;
var particles =[];
for (var i = 0; i < NumParticles; i++) {
particles[i] = {
x: Math.floor(Math.random()*W),
y: Math.floor(Math.random()*H),
r: Math.floor(Math.random()*7+1),
path: circlePath(Math.random()*7+1),
}
}
function draw(ctx) {
ctx.fillStyle = "#ADD8E6";
ctx.fillRect(0, 0, W-1, H-1);
ctx.fillStyle = "#FFFFFF";
angle += 0.0039;
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
p.x += Math.floor(Math.sin(angle)*5.0);
p.y += 0.6*p.r;
if (p.x > W) {
p.x-=W;
}
if (p.x < 0) {
p.x += W;
}
if(p.y>(H+1)){
p.y = 0;
}
if (HAS_PATH) {
ctx.save();
ctx.translate(p.x, p.y);
ctx.fill(p.path);
ctx.restore();
} else {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.arc(p.x, p.y, p.r, 0, 2*Math.PI, true);
ctx.closePath();
ctx.fill();
}
};
ticks++;
if (IS_SKV8) {
inval();
}
}
function fps() {
console.log(ticks);
ticks = 0;
setTimeout(fps, 1000);
}
setTimeout(fps, 1000);
return draw;
}();
if (!IS_SKV8) {
window.onload = function(){
var canvas = document.getElementById("snow");
var ctx = canvas.getContext("2d");
function drawCallback() {
onDraw(ctx);
setTimeout(drawCallback, 1);
}
setTimeout(drawCallback, 1);
}
}
console.log("HAS_PATH: " + HAS_PATH);

View File

@ -1,23 +0,0 @@
/**
* @fileoverview Sample onDraw script for use with SkV8Example.
*/
var onDraw = function(){
var tick = 0;
function f(canvas) {
tick += 0.1;
canvas.fillStyle = '#0000ff';
canvas.fillRect(100, 100, Math.sin(tick)*100, Math.cos(tick)*100);
inval();
};
function onTimeout() {
print(tick*10, " FPS");
setTimeout(onTimeout, 1000);
tick=0;
}
setTimeout(onTimeout, 1000);
return f;
}();