mirror of
https://github.com/scratchfoundation/paper.js.git
synced 2025-01-01 02:38:43 -05:00
Support running of PaperScript .pjs files.
This commit is contained in:
parent
0f7406f7f4
commit
25cb4a7dd1
1 changed files with 26 additions and 6 deletions
|
@ -1,18 +1,28 @@
|
|||
var context = require('vm').createContext({
|
||||
var fs = require('fs'),
|
||||
vm = require('vm'),
|
||||
path = require('path');
|
||||
|
||||
// Create the context within which we will run the source files:
|
||||
var context = vm.createContext({
|
||||
options: {
|
||||
server: true,
|
||||
version: 'dev'
|
||||
},
|
||||
// Node Canvas library: https://github.com/learnboost/node-canvas
|
||||
Canvas: require('canvas'),
|
||||
// Copy over global variables:
|
||||
console: console,
|
||||
require: require,
|
||||
__dirname: __dirname,
|
||||
__filename: __filename,
|
||||
// Used to load and run source files within the same context:
|
||||
include: function(uri) {
|
||||
var source = require('fs').readFileSync(__dirname + '/' + uri);
|
||||
// For relative includes, we save the current directory and then add
|
||||
// the uri directory to __dirname:
|
||||
var source = fs.readFileSync(path.resolve(__dirname, uri), 'utf8');
|
||||
// For relative includes, we save the current directory and then
|
||||
// add the uri directory to __dirname:
|
||||
var oldDirname = __dirname;
|
||||
__dirname = __dirname + '/' + uri.replace(/[^/]+$/, '');
|
||||
require('vm').runInContext(source, context, uri);
|
||||
__dirname = path.resolve(__dirname, path.dirname(uri));
|
||||
vm.runInContext(source, context, uri);
|
||||
__dirname = oldDirname;
|
||||
}
|
||||
});
|
||||
|
@ -28,4 +38,14 @@ context.Base.each(context, function(val, key) {
|
|||
});
|
||||
context.PaperScope.prototype['Canvas'] = context.Canvas;
|
||||
|
||||
require.extensions['.pjs'] = function(module, uri) {
|
||||
var source = context.PaperScript.compile(fs.readFileSync(uri, 'utf8'));
|
||||
var envVars = 'var __dirname = \'' + path.dirname(uri) + '\';' +
|
||||
'var __filename = \'' + uri + '\';';
|
||||
vm.runInContext(envVars, context);
|
||||
var scope = new context.PaperScope();
|
||||
context.PaperScript.evaluate(source, scope);
|
||||
module.exports = scope;
|
||||
};
|
||||
|
||||
module.exports = new context.PaperScope();
|
Loading…
Reference in a new issue