Skip to content

Instantly share code, notes, and snippets.

@kou
Created July 24, 2017 02:48
Show Gist options
  • Save kou/d3c87fbeb701202ad0b5d7c7daeb8d01 to your computer and use it in GitHub Desktop.
Save kou/d3c87fbeb701202ad0b5d7c7daeb8d01 to your computer and use it in GitHub Desktop.
Save graph generated by rbplotly as PNG by webkit2-gtk
#!/usr/bin/env ruby
require "rbplotly"
require "webkit2-gtk"
x = [0, 1, 2, 3, 4]
trace0 = { x: x, y: [0, 2, 1, 4, 3], type: :scatter, mode: :lines }
trace1 = { x: x, y: [4, 1, 3, 0, 2], type: :scatter, mode: :'markers+lines' }
data = [trace0, trace1] # data must be an array
layout = { width: 500, height: 500 }
plot = Plotly::Plot.new(data: data, layout: layout)
plot.layout.height = 300 # You can assign plot's attributes.
module Plotly
class Plot
def to_html_data
id = UUIDTools::UUID.random_create.to_s
html = Offline::HTML.new(id,
@data.map(&:to_h),
layout: @layout.to_h,
config: {},
embedded: false)
html.render
end
end
end
main_loop = GLib::MainLoop.new
base_path = "/tmp/x"
view_context = WebKit2Gtk::WebContext.new(ephemeral: true)
view = WebKit2Gtk::WebView.new(context: view_context)
window = Gtk::OffscreenWindow.new
window.add(view)
window.set_default_size(plot.layout.width, plot.layout.height)
window.show_all
view.load_html(plot.to_html_data)
view.signal_connect("load-changed") do |_, load_event|
case load_event
when WebKit2Gtk::LoadEvent::FINISHED
view.get_snapshot(:full_document, :none) do |_, result|
main_loop.quit
snapshot_surface = view.get_snapshot_finish(result)
snapshot_surface.write_to_png("#{base_path}.png")
end
end
end
view.signal_connect("load-failed") do |_, _, failed_uri, error|
main_loop.quit
message = "failed to load URI: #{failed_uri}: "
message << "#{error.class}(#{error.code}): #{error.message}"
puts(message)
true
end
main_loop.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment