medievalmatt
medievalmatt

Reputation: 491

diagonal image overlay via css/javascript

I want to create a div overlay, set at 5% opacity, which creates a diagonal bounding box around the first line of text in this image. It seems to me that if I have the x,y coordinates for the four corners I should be able to create the overlay but I cannot figure out what the proper syntax would be to mark out the div. Am I wrong in thinking this can be done, and if not can someone point me at some methods for doing so?

Image that I want to draw the overlay on

Upvotes: 1

Views: 1432

Answers (1)

6502
6502

Reputation: 114539

Instead of using a canvas and javascript for simple cases you can use instead the transform property of css divs. For example with

#diag {
    background-color: rgba(255, 0, 255, 0.25);
    width: 700px;
    height: 60px;
    position: absolute;
    left: 100px;
    top: 160px;
    transform: rotate(2deg) skew(30deg)
}

you can get a div positioned on the first line of the text in the image that can be styled easily with CSS for borders and that can be used directly for events (hover, clicks).

If you need to specify 4 corners however just a single transform is not enough in general and you have to draw your overlay in a canvas placed over the image. This works because a canvas is by default transparent and only what you explicitly draw will be visible leaving the image untouched in other areas. For example using:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
ctx.beginPath();
ctx.moveTo(166, 282);
ctx.lineTo(855, 296);
ctx.lineTo(897, 351);
ctx.lineTo(212, 349);
ctx.closePath();
ctx.fillStyle = "rgba(0, 255, 0, 0.25)";
ctx.strokeStyle = "#0F0";
ctx.lineWidth = 4;
ctx.fill();
ctx.stroke();

I've highlighted the third row in green (fill command) also adding a border (stroke command).

fiddle output

http://jsfiddle.net/hr9afs4z/1/

Upvotes: 1

Related Questions