Search code examples
pythonseleniumselenium-chromedriverdrawingaction

Drawing characters using Python Selenium


I am planning to draw characters A B C D in https://sketchtoy.com/ canvas using Selenium Action chains,

import time
from selenium.webdriver.common.action_chains import ActionChains

def draw(action, offset_list):
    for offset in offset_list:
        action.click_and_hold().move_by_offset(offset[0], offset[1]).perform()
        print(f'Moving to {offset[0]}, {offset[1]}')
        time.sleep(1)
        action.release().perform()

def main(driver):
        driver.get("https://sketchtoy.com/")
        action = ActionChains(driver)
        element = driver.find_element_by_xpath("html/body/div[1]/div[5]/div[2]/canvas")
        action.move_to_element(element).perform()
        draw(action, [(-100, -100), (100, -100), (-100, 100), (100, 100), (-100, -100)])

This is the code with which I'm expecting it to draw a square shape by moving to positions similar to an X-Y graphs.

But it seems to be drawing a triangle.

Triangle like image

I am not sure how or why this is running like that.


Solution

  • How I moved to coordinates and draw using Actions.

    def draw(action, element, offset_list):
        action.click_and_hold(element)
        for offset in offset_list:
            action.move_by_offset(offset[0], offset[1])
            time.sleep(1)
        action.release().perform()
    
    def main(driver):
        driver.get("https://sketchtoy.com/")
        action = ActionChains(driver)
        element = driver.find_element_by_xpath("html/body/div[1]/div[5]/div[2]/canvas")
        action.move_to_element(element).perform()
        draw(action, element, [(0,20), (0,5), (20, 0), (0,-5), (0,-20), (0, -5), (-20, 0), (0, 10)])
        draw(action, element, [(70, 0), (5, 0), (0, 25), (-20, 0), (0, -5)])
        draw(action, element, [(0, 60), (0, 10), (75, 0), (0, -10), (-5, 0)])