I would like to add lines on an image using CSS3 and HTML5 Canvas. I came across a tutorial and demo that utilizes an html div:
However, when attempting this effect on an image, the line appears outside of the image.
How can I ensure that the line is drawn directly on top of the image?
Additionally, I need the line width to be responsive. For example, if I resize the browser window (which dynamically resizes the image with Javascript), the pixel width of the line should also adjust accordingly.
Should I switch to using Canvas HTML5 instead? What about browser compatibility?
The full code is provided below:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8>
<title>Lines with CSS</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script>
<style>
div.line{
-webkit-transform-origin: 0 50%;
-moz-transform-origin: 0 50%;
transform-origin: 0 50%;
height: 5px; /* Line width of 3 */
background: #948C79; /* Black fill */
opacity: 0.5;
box-shadow: 0 0 8px #B99B7E;
/* Animation for rotation effects: */
-webkit-transition: -webkit-transform 1s;
-moz-transition: -moz-transform 1s;
transition: transform 1s;
}
div.line:hover{
background: #C30;
box-shadow: 0 0 8px #C30;
opacity: 1;
}
div.line.active{
background: #666;
box-shadow: 0 0 8px #666;
opacity: 1;
}
</style>
<script>
function createLine(x1,y1, x2,y2){
var length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
var angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
var transform = 'rotate('+angle+'deg)';
var line = $('<div>')
.appendTo('#page')
.addClass('line')
.css({
'position': 'relative',
'transform': transform
})
.width(length)
.offset({left: x1, top: y1});
return line;
} // function
</script>
</head>
<body>
<p>Lines with CSS</p>
<input type="button" value="Draw line" onClick="createLine(0,0,20,20);" />
<div id="page" style="height:auto;"><p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Man_o%27war_cove_near_lulworth_dorset_arp.jpg/300px-Man_o%27war_cove_near_lulworth_dorset_arp.jpg" class="image" /></p></div>
</body>
The jsfiddle link is available here: https://jsfiddle.net/30xh1xpm/ (please note that it does not draw the line).