Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Text inside a Canvas using Webdriver or Protractor

I have a canvas and i want to get the text inside a canvas. I can mouse over inside the canvas but not sure how to get the text. Uploaded the image from which i need to validate the scenario using Protractor Please help?

<canvas style="background-color: rgb(255, 255, 255); width: 395px; height: 194px; cursor: auto;" width="592" height="291"/>

enter image description here

like image 768
anuvrat singh Avatar asked Apr 25 '17 11:04

anuvrat singh


People also ask

How do you get text on canvas?

Drawing Text on the Canvas To draw text on a canvas, the most important property and methods are: font - defines the font properties for the text. fillText(text,x,y) - draws "filled" text on the canvas. strokeText(text,x,y) - draws text on the canvas (no fill)

Can selenium interact with canvas?

Canvas has several methods for drawing paths, boxes, circles, characters, and adding images. This element is used to build drawing by using JavaScript. Solution: Since drawing is an action, we can use the Selenium Webdriver's action class to automate the canvas feature.


1 Answers

The basics are that you can't with Selenium. the CANVAS tag is like an applet in the page. It doesn't actually contain any HTML. There are a few options:

  1. If you have access to the devs, you can have them expose an API for you so that you can access text, etc. using Javascript from your Selenium script. If it's part of some library, etc. the library itself may provide an API that you can use. This is the most reliable option.

  2. For executing actions, you can use coordinates. You can base all click, etc. actions off coordinates but this is highly dependent on the browser rendering, screen resolution, etc. This will not help you get text out of the CANVAS though.

  3. For the text, you really don't have any options to get the text directly. You could take screenshots and verify the text after the run is complete but that's about your best option. If you wanted to get really fancy, depending on the text, etc. you may be able to find an OCR library that will be able to extract the text from the screenshot that you took.

like image 161
JeffC Avatar answered Sep 29 '22 01:09

JeffC