Skip to content

Instantly share code, notes, and snippets.

@mataki
Created May 7, 2012 09:52
Show Gist options
  • Save mataki/2626985 to your computer and use it in GitHub Desktop.
Save mataki/2626985 to your computer and use it in GitHub Desktop.
require "rubygems"
require "capybara-webkit"
require "mini_magick"
class WebkitScreenshot
def initialize
@browser = Capybara::Driver::Webkit::Browser.new
end
def browser
@browser
end
def visit(url)
browser.visit(url)
end
# Result sample: {"bottom"=>186, "height"=>110, "left"=>0, "right"=>276, "top"=>76, "width"=>276}
def rect(elem_id)
browser.evaluate_script <<-EOF
var elem = document.getElementById('#{elem_id}');
Capybara.reflow(elem);
elem.getBoundingClientRect();
EOF
end
# Result sample: {"x"=>953, "y"=>42}
def offset(elem_id)
browser.evaluate_script <<-EOF
var elem = document.getElementById('#{elem_id}');
Capybara.reflow(elem);
Capybara.centerPostion(elem);
EOF
end
def output(options = {})
filename = options[:filename] || "out.png"
width = options[:width] || 1000
height = options[:height] || 10
browser.render(filename, width, height)
filename
end
def output_by_elem(elem_id, options = {})
filename = options[:filename] || "elem.png"
img = MiniMagick::Image.open(output)
img.crop(crop_param(elem_id))
img.write(filename)
end
WRAP_WIDTH = 40
def crop_param(elem_id)
params_rect = rect(elem_id)
params_offset = offset(elem_id)
width = params_rect['width'] + WRAP_WIDTH
height = params_rect['height'] + WRAP_WIDTH
offset_x = params_offset['x'] - params_rect['width']/2 - WRAP_WIDTH/2
offset_x = 0 if offset_x < 0
offset_y = params_offset['y'] - params_rect['height']/2 - WRAP_WIDTH/2
offset_y = 0 if offset_y < 0
"#{width}x#{height}+#{offset_x}+#{offset_y}"
end
end
if __FILE__ == $0
ws = WebkitScreenshot.new
ws.visit "http://www.google.co.jp/"
ws.output_by_elem('hplogo', filename: "google.png")
ws.visit "http://www.sonicgarden.jp/"
ws.output_by_elem('nav', filename: "nav.png")
ws.visit "http://www.sonicgarden.jp/"
ws.output_by_elem('facebook', filename: "facebook.png")
ws.visit "https://www.facebook.com/"
ws.output_by_elem('loginbutton', filename: "loginbutton.png")
ws.visit "https://www.facebook.com/"
ws.output_by_elem('registration_container', filename: "registration_container.png")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment