Skip to content

Instantly share code, notes, and snippets.

@dtinth
Created February 19, 2010 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtinth/308771 to your computer and use it in GitHub Desktop.
Save dtinth/308771 to your computer and use it in GitHub Desktop.
Canvas Renderer
#!/usr/bin/env python
import sys
import json
import base64
try:
import WebKit
view = WebKit.WebView.alloc().init()
wso = view.windowScriptObject()
evalJS = wso.evaluateWebScript_
except:
import webkit
import gtk
gtk.gdk.threads_init()
view = webkit.WebView()
def evalJS(js):
view.execute_script ('document.title=eval(' + json.dumps(js, False, False) + ')')
return view.get_main_frame().get_title()
if len(sys.argv) > 1:
input = open(sys.argv[1], 'r')
else:
input = sys.stdin
result = json.loads(unicode(evalJS(u'''(function() {
var canvas, ctx, files = [], w, h;
function newFile(aw, ah) {
canvas = document.createElement('canvas');
ctx = canvas.getContext('2d');
canvas.width = w = aw;
canvas.height = h = ah;
}
function saveFile(filename) {
if (filename === undefined) filename = 'Untitled';
files.push ([filename, canvas.toDataURL()]);
}
newFile (1, 1);
try {
eval (''' + json.dumps(input.read(), True, False) + u''');
} catch (e) {
return JSON.stringify(['error', e.toString()]);
}
return JSON.stringify(['success', files]);
})() + '';''')));
if result[0] == 'error':
sys.stderr.write ('Error in your code: ' + result[1] + '\n')
else:
for file in result[1]:
print 'Writing file ' + file[0] + '.png'
fp = open(file[0] + '.png', 'wb')
fp.write (base64.b64decode(file[1][file[1].index(',') + 1:]))
fp.close ()
newFile (200, 100);
var gradient = ctx.createLinearGradient(0, 0, 0, h);
gradient.addColorStop (0, '#f00');
gradient.addColorStop (1, '#ff0');
ctx.fillStyle = gradient;
ctx.fillRect (0, 0, w, h);
ctx.fillStyle = '#fff';
ctx.font = 'bold 15pt Verdana';
ctx.textAlign = 'center';
ctx.textBaseLine = 'middle';
ctx.shadowColor = 'black';
ctx.shadowBlur = 10;
ctx.shadowOffsetY = 3;
ctx.fillText ('Hello World!', w / 2, h / 2);
saveFile ('test');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment