I have designed a canvas that is created with functionality from the pywebview
package. On this canvas, I attempt to use paper.js
to draw a Path
, then output the resulting rendered HTML to an image popup. The Path
does not render on the page, although the same code seems to work on an interactive snippet tester on the Paper.js website. This is my code so far:
import io
from PIL import Image
import base64
import webview
def extract_image(width, height, path=[(100, 100)]):
color = 'red'
def callback(window):
window.html = f"""
<script type="text/javascript" src="js/paper.js"></script>
<canvas id="myCanvas" width="{width}" height="{height}"></canvas>
"""
js_code = f"""
var canvas = document.getElementById("myCanvas")
paper.setup(canvas)
var start = new paper.Point({path[0][0]}, {path[0][1]})
var end = new paper.Point({path[0][0] + 1}, {path[0][1]})
var path = new paper.Path({{
segments: [start, end],
strokeColor: '{color}',
strokeCap: 'round',
strokeJoin: 'round',
strokeWidth: 10
}})
path.add(new paper.Point(200, 200))
paper.project.activeLayer.addChild(path)
paper.view.draw()
"""
print(js_code)
print(window.evaluate_js(js_code))
data_url = window.evaluate_js("canvas.toDataURL()")
print(f"data url is: {data_url}")
# Extract the base64 encoded image data from the data URL
base64_data = data_url.split(",")[1]
# Decode the base64 data and create a PIL image from it
image_data = io.BytesIO(base64.b64decode(base64_data))
image = Image.open(image_data)
# Display the image
image.show()
window.destroy()
return callback
def extract_canvas_to_image():
return webview.create_window('Hello world', frameless=True, hidden=True)
if __name__ == '__main__':
window = extract_canvas_to_image()
webview.start(extract_image(400, 400), window)
How can I get my Path to render properly?
maybe you should load paper.js with a cdn:
change:
<script type="text/javascript" src="js/paper.js"></script>
to:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.17/paper-full.min.js"></script>