ILikeTacos
ILikeTacos

Reputation: 18676

draw rectangle over html with javascript

I know there's a similar question here, but neither the question nor the answer have any code.

What I want to do, is to port this functionality to a 100% Javascript solution. Right now I'm able to draw a rectangle on top of HTML content using PHP.

I scrape a website with CasperJS, take a snapshot, send the snapshot path back to PHP along with a json object that contains all the information necessary to draw a rectangle with GD libraries. That works, but now I want to port that functionality into Javascript.

The way I'm getting the rectangle information is using getBoundingClientRect() that returns an object with top,bottom,height, width, left,and right.

Is there any way to "draw" the HTML of the website to a canvas element, and then draw a Rectangle on that canvas element? Or is there any way to draw a rectangle on top of the HTML using Javascript?

Hope my question is clear enough.

This is the function that I'm using to get the coordinates of the elements that I want to draw a Rectangle around.

function getListingRectangles() {
    return Array.prototype.map.call(document.querySelectorAll('.box'), function(e) {
        return e.getBoundingClientRect();
});

Upvotes: 5

Views: 24486

Answers (1)

Borre Mosch
Borre Mosch

Reputation: 4564

You can create a canvas element and place it on top of the HTML page:

//Position parameters used for drawing the rectangle
var x = 100;
var y = 150;
var width = 200;
var height = 150;

var canvas = document.createElement('canvas'); //Create a canvas element
//Set canvas width/height
canvas.style.width='100%';
canvas.style.height='100%';
//Set canvas drawing area width/height
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//Position canvas
canvas.style.position='absolute';
canvas.style.left=0;
canvas.style.top=0;
canvas.style.zIndex=100000;
canvas.style.pointerEvents='none'; //Make sure you can click 'through' the canvas
document.body.appendChild(canvas); //Append canvas to body element
var context = canvas.getContext('2d');
//Draw rectangle
context.rect(x, y, width, height);
context.fillStyle = 'yellow';
context.fill();

This code should add a yellow rectangle at [100, 150] pixels from the top left corner of the page.

Upvotes: 9

Related Questions