How to draw rectangle box over an image present inside div? - javascript

I have developed a page where I dynamically import images and display them inside a div tag. Now i wanted to draw an rectangle over the image, and it should start from any point on the image.
I referred many sources and tried to implement the idea from it.
<style>
#rubberBand {
position: absolute;
visibility: hidden;
width: 0px; height: 0px;
border: 2px solid red;
}
</style>
<div class="imageside" id="picture"> </div>
<div ID="rubberBand"></div>
In the above code, the image is display at the div id "picture". Till this part of the code works fine.
var pic, rubber, pt = { x: 0, y: 0 };
picture= getpicture();
function getpicture(){
pic= document.getElementById('picture')
pic.innerHTML= getgImage(event.target.dataset.number);
}
function startRubber (evt) {
var ev = evt || window.event,
rs = rubber.style,
bb = pic.innerHTML.getBoundingClientRect();
console.dir(ev);
rs.left = bb.left + 'px';
rs.top = bb.top + 'px';
rs.width = bb.width + 'px';
rs.height = bb.height + 'px';
rs.display = 'block';
pt = { x: ev.clientX - bb.left, y: ev.clientY - bb.top };
return false;
}
function stopRubber () {
rubber.style.display = 'none';
}
function moveRubber (evt) {
var ev = evt || window.event;
rubber.style.left = (evt.clientX - pt.x) + 'px';
rubber.style.top = (evt.clientY - pt.y) + 'px';
}
rubber = document.getElementById('rubberBand');
pic = document.getElementById('picture').innerHTML;
pic.onmousedown = startRubber;
document.onmouseup = stopRubber;
document.onmousemove = moveRubber;
In the above code, the function getpicture() is responsible to display the images dynamically. When i execute the above code, the image displays on the page, but I am not able to draw the rectangle over the image. In console, no errors. Can someone help me out with problem and help me to draw the rectangle over the image.

check this out.
https://jsfiddle.net/2at9n7ye/3/
your issue is that you are accessing the pic variable before you load it.
var pic, rubber, pt = {
x: 0,
y: 0
};
picture = getpicture();
function getpicture() {
pic = document.getElementById('picture');
pic.innerHTML = "<img src='https://i.imgur.com/mvMlmMb.jpg' id='img' width='100px' height='100px'/>";
}
function startRubber(evt) {
var ev = evt || window.event,
rs = rubber.style,
bb = pic.getBoundingClientRect
rs.left = bb.left + 'px';
rs.top = bb.top + 'px';
rs.width = bb.width + 'px';
rs.height = bb.height + 'px';
rs.display = 'block';
pt = {
x: ev.clientX - bb.left,
y: ev.clientY - bb.top
};
return false;
}
function stopRubber() {
rubber.style.display = 'none';
}
function moveRubber(evt) {
var ev = evt || window.event;
rubber.style.left = (evt.clientX - pt.x) + 'px';
rubber.style.top = (evt.clientY - pt.y) + 'px';
}
(function() {
rubber = document.getElementById('rubberBand');
pic = document.getElementById('picture');
pic.addEventListener("mousedown", startRubber);
document.addEventListener("mouseup", stopRubber);
document.addEventListener("mousemove", moveRubber);
})();

Related

Safari & Chrome Giving diffrent results to the same script (document.querySelector)

Why are Safari and Chrome giving different results when using document.querySelector in the same script?
What I'm trying to do is display the image next to the link when hovering over it. The image should be displayed next to the link.
In Safari, the image is displayed properly from the left corner, but in Chrome, when I scroll down and point at the link, the image is displayed from unexpected angles.
JavaScript:
let attached = false;
function showImage() {
const image = document.querySelector('img');
if (image && !attached) {
attached = true;
image.style.display = 'block';
document.addEventListener('pointermove', function(event) {
image.style.left = event.x + 'px';
image.style.top = event.y + 'px';
});
}
}
function hideImage() {
const image = document.querySelector('img');
if (image && attached) {
attached = false;
image.style.display = 'none';
document.removeEventListener('pointermove', function(event) {
image.style.left = event.x + 'px';
image.style.top = event.y + 'px';
});
}
}
CSS:
img{
position: fixed;
display: none;
pointer-events: none;
width: 640px;
height: auto;
}
I've tried changing the code to:
let attached = false;
const getElmtImage = (elmt) => {
return elmt.querySelector("img")
}
const followMouse = (elmt, event) => {
elmt.style.left = event.x + "px";
elmt.style.top = event.y + "px";
}
function showImage(elmt) {
const image = getElmtImage(elmt)
if (!attached) {
attached = true;
image.style.display = "block";
document.addEventListener("pointermove", function(event) {
followMouse(image, event)
});
}
}
function hideImage(elmt) {
const image = getElmtImage(elmt)
attached = false;
image.style.display = "none";
document.removeEventListener("pointermove", followMouse);
}```
I have conducted some testing, and it appears that Chrome and Safari handle events differently (based on my testing, although I could be mistaken). In Safari, event.x works, whereas in Chrome only event.pageY works. To work around this issue, I first check the browser type and then execute the appropriate functions. This approach may not be the cleanest, but it is effective. If you have a better idea of how to handle this situation, please share it.
let attached = false;
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
// chrome
function showImage() {
const image = document.querySelector('img');
if (image && !attached) {
attached = true;
image.style.display = 'block';
document.addEventListener('mousemove', function(event) {
image.style.left = event.pageX + 'px';
image.style.top = event.pageY + 'px';
});
}
}
function hideImage() {
const image = document.querySelector('img');
if (image && attached) {
attached = false;
image.style.display = 'none';
document.removeEventListener('mousemove', function(event) {
image.style.left = event.pageX + 'px';
image.style.top = event.pageY + 'px';
});
}
} } else {
// safari
function showImage() {
const image = document.querySelector('img');
if (image && !attached) {
attached = true;
image.style.display = 'block';
document.addEventListener('pointermove', function(event) {
image.style.left = event.x + 'px';
image.style.top = event.y + 'px';
});
}
}
function hideImage() {
const image = document.querySelector('img');
if (image && attached) {
attached = false;
image.style.display = 'none';
document.removeEventListener('pointermove', function(event) {
image.style.left = event.x + 'px';
image.style.top = event.y + 'px';
});
}
} }
}

How to use vanilla script to bounce elements from each other

I've tried adding the top and left changes, and margin (with different positioning changes too) changes to each element if one approaches another but only the margin change works once. Is there a way to make them work more consistently?
This is where I've used a function to add the event listeners:
var three = document.getElementById('three');
var test = document.getElementById('test');
var two = document.getElementById('two');
var obj = null;
function testmovea(object, event) {
obj = document.getElementById(object.id);
document.addEventListener("mousemove", move);
}
function move(event) {
obj.innerText = event.clientX + ' ' + event.clientY;
obj.style.position = 'absolute';
obj.style.left = event.clientX + "px";
obj.style.top = event.clientY + "px";
three.addEventListener('mouseover', borders);
three.addEventListener('mouseleave', bordersOff);
two.addEventListener('mouseenter', bTwo);
test.addEventListener('mouseenter', bTest);
two.addEventListener('mouseleave', bTwoReset);
test.addEventListener('mouseleave', bTestReset);
document.addEventListener("mouseup", stopMove);
}
function bTwo() {
two.style.margin = "10%";
}
function bTwoReset() {
two.style.margin = "0%";
}
function bTest() {
test.style.margin = "10%";
}
function bTestReset() {
test.style.margin = "0%"
}
This is the mouse stop event I use:
function stopMove() {
document.removeEventListener('mousemove', move);
test.removeEventListener('mouseover', bTest);
two.removeEventListener('mouseover', bTwo);
test.removeEventListener('mouseleave', bTestReset);
two.removeEventListener('mouseleave', bTwoReset);
}
the testmovea function relies on a onmousedown property defined for a DOM element of the page
Update:
I've managed to get it to partially work:
function collide(el1, el2) {
if(twoBoundX >= threeBoundY || threeBoundY >= twoBoundX) {
two.style.margin = + event.clientX + "px";
two.style.margin = + event.clientY + "px";
}
}
where twoBoundX and threeBoundY are getBoundingClientRect() of the respective elements
Here's the full code snippet:
<html>
<head>
<style type="text/css">
#two {
border: 1px solid black;
padding: 1%;
margin: 1%;
margin-top: 10%;
width: 10%;
}
#three {
border: 1px solid black;
padding: 1%;
margin-top: 2%;
}
</style>
</head>
<body>
<div id="two" onmousedown="testmovea(this, event)" onclick="currentTwoPos()">
stop movement
</div>
<div id="three" onmousedown="testmovea(this)">Expand div</div>
<div style="height: 30%" id="two" contenteditable="true">
some contenteditable</div>
</body>
<script>
var three = document.getElementById('three');
var two = document.getElementById('two');
const twoBound = two.getBoundingClientRect();
const threeBound = three.getBoundingClientRect();
var threeBoundX = threeBound.x;
var threeBoundY = threeBound.y;
var twoBoundX = twoBound.x;
var twoBoundY = twoBound.y;
var twoBoundBottom = null;
var twoBoundTop = null;
var obj = null;
function collide(el1, el2) {
if(twoBoundX >= threeBoundY || threeBoundY >= twoBoundX) {
two.style.left = event.clientX + "px";
two.style.top = event.clientY + "px";
three.style.left = event.clientX + "px";
three.style.top = event.clientY + "px";
}
}
function testmovea(object, event) {
obj = document.getElementById(object.id);
document.addEventListener("mousemove", move);
}
function move(event) {
obj.innerText = event.clientX + ' ' + event.clientY;
obj.style.position = 'absolute';
obj.style.left = event.clientX + "px";
obj.style.top = event.clientY + "px";
two.addEventListener('mouseover', collide);
three.addEventListener('mouseover', collide);
document.addEventListener("mouseup", stopMove);
}
function stopMove() {
mousemove = false;
document.removeEventListener('mousemove', move);
three.removeEventListener('mouseover', collide);
two.removeEventListener('mouseover', collide);
}
</script>
</html>
collision detection
You need to define a function that checks whether two of your shapes collide. If you only have rectangles whose vertex are parallel with the OX and OY vertexes, it would look like this:
function areColliding(r1, r2) {
return !(
(r1.x > r2.x + r2.w) ||
(r1.x + r1.w < r2.x) ||
(r1.y > r2.y + r2.h) ||
(r1.y + r1.h < r2.y)
);
}
Of course, if some rotation or even other shapes are involved into your problem, then you need to extend/adjust the collision detector accordingly.
a shared function
You need to create a function that would receive the current status of the elements and the move that happens. It would look like this:
function handleMove(currentPositions, proposedPositions) {
while (!validPositions(proposedPositions)) {
proposedPositions = generateNewPositions(currentPositions, handleCollisions(proposedPositions));
}
refreshUI(proposedPositions);
}
currentPositions is the set of positions your elements currently have
proposedPositions is the set of positions your elements are going to have if there are no collisions
validPositions checks for any pair of shapes that would collide and returns true if none of those pair collide and false if at least one such pair collides
proposedPositions is being refreshed while there are still collisions
generateNewPositions is your handler for collision-based changes
handleCollisions effectuates changes to avoid collision
refreshUI refreshes the UI
event handling
your mouse events should handle change updates by loading all the positions of your elements and calling this shared functionality.
Note: If you have further problems, then you might need to create a reproducible example so we could see your exact structure, styling and code as well.
<html>
<head>
<style type="text/css">
#two {
border: 1px solid black;
width: 10%;
padding: 1%;
margin: 1%;
margin-top: 10%;
}
#three {
border: 1px solid black;
padding: 1%;
margin-top: 2%;
}
</style>
</head>
<body>
<div id="two" onmousedown="testmovea(this, event)" style="position: relative;">
stop movement
</div>
<div id="three" onmousedown="testmovea(this)" style="position: relative;">Expand div</div>
<!--<div style="height: 30%; position: relative;" id="two" contenteditable="true">
some contenteditable</div>-->
</body>
<script>
var three = document.getElementById('three');
var two = document.getElementById('two');
let moveStarted = false;
function collide() {
const first = two.getBoundingClientRect();
const second = three.getBoundingClientRect();
if (!(
(first.x + first.width < second.x) ||
(second.x + second.width < first.x) ||
(first.y + first.height < second.y) ||
(second.y + second.height < first.y)
)) {
two.style.left = event.clientX + "px";
two.style.top = event.clientY + "px";
three.style.left = event.clientX + "px";
three.style.top = event.clientY + "px";
}
}
function testmovea(object, event) {
obj = document.getElementById(object.id);
if (!moveStarted) {
document.addEventListener("mousemove", move);
moveStarted = true;
}
}
function move(event) {
//obj.innerText = event.clientX + ' ' + event.clientY;
obj.style.left = event.clientX + "px";
obj.style.top = event.clientY + "px";
if (!obj.classList.contains("dragged")) obj.classList.add("dragged");
collide(obj);
}
function stopMove() {
mousemove = false;
if (moveStarted) {
document.removeEventListener('mousemove', move);
moveStarted = false;
}
}
document.addEventListener("mouseup", stopMove);
</script>
</html>

How to prevent an element from moving diagonally

The element moves all the directions (top, right, bottom, left) including diagonally. I do not want it to move diagonally.
HTML
<body onload="move('theDiv')">
<div class="container">
<div id="theDiv" class="theDiv"></div>
</div>
</body>
Javascript
var dragValue;
function move(id) {
var element = document.getElementById("theDiv");
element.style.position = "sticky";
element.onmousedown = function() {
dragValue = element;
};
}
document.onmouseup = function(e) {
dragValue = null;
};
document.onmousemove = function(e) {
var x = e.pageX,
y = e.pageY;
dragValue.style.transform = "transltex(" + x + "px)";
dragValue.style.transform = "transltey(" + y + "px)";
};
Use lastPoint.
1. When the value of x in the current position is not equal to the value of x in the old position, that is, moving in the direction of the x-axis.
2. When the value of y of the current position is not equal to the value of y of the old position, it means moving in the direction of the y-axis.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
.theDiv {
background-color: blue;
height: 100px;
width: 150px;
position: fixed;
top: 0;
left: 0;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body onload="move('theDiv')">
<div id="theDiv" class="theDiv"></div>
<script>
var dragValue;
var lastPoint;
function move(id) {
var element = document.getElementById("theDiv");
element.onmousedown = function(e) {
dragValue = element;
lastPoint = e;
lastPoint.pageX = lastPoint.pageX - ($('#theDiv').width() / 2);
lastPoint.pageY = lastPoint.pageY - ($('#theDiv').height() / 2);
};
}
document.onmouseup = function(e) {
dragValue = null;
lastPoint = null;
};
document.onmousemove = function(e) {
if (dragValue != null) {
var x = e.pageX - ($('#theDiv').width() / 2),
y = e.pageY - ($('#theDiv').height() / 2);
if (lastPoint.pageX == e.pageX)
dragValue.style.top = y + "px";
else
dragValue.style.left = x + "px";
lastPoint = e;
}
};
</script>
</body>
</html>
I had to change your code a bit to be able to run it. You can easily use this code or use it with your own code

HTML Canvas & Javascript - Hover and Click Events

Below is a script which defines two functions that draw 4 rectangular buttons and 1 circular button respectively. I am trying to implement specific Hover and Click functionality into the buttons (as described in the script alerts) but I am at a bit of a loss as to how to do this. I tried calling the makeInteractiveButton() functions on each click but this caused a lot of odd overlap and lag. I want the script to do the following:
If the circular button is hovered, I would like it's fillColour to change and if it is clicked I would like it to change again to the colours described in the code (#FFC77E for hover, #FFDDB0 for clicked). This should only happen for the duration of the hover or click.
HTML:
<html lang="en">
<body>
<canvas id="game" width = "750" height = "500"></canvas>
<script type='text/javascript' src='stack.js'></script>
</body>
</html>
JavaScript:
var c=document.getElementById('game'),
canvasX=c.offsetLeft,
canvasY=c.offsetTop,
ctx=c.getContext('2d')
elements = [];
c.style.background = 'grey';
function makeInteractiveButton(x, strokeColor, fillColor) {
ctx.strokeStyle=strokeColor;
ctx.fillStyle=fillColor;
ctx.beginPath();
ctx.lineWidth=6;
ctx.arc(x, 475, 20, 0, 2*Math.PI);
ctx.closePath();
ctx.stroke();
ctx.fill();
elements.push({
arcX: x,
arcY: 475,
arcRadius: 20
});
}
b1 = makeInteractiveButton(235, '#FFFCF8', '#FFB85D');
c.addEventListener('mousemove', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if cursor in rect
alert('Rectangle should undergo 5 degree rotation and 105% scale');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if cursor in circle
alert('Set b1 fillColour to #FFC77E.');
}
});
}, false);
c.addEventListener('click', function(event) {
x=event.pageX-canvasX; // cursor location
y=event.pageY-canvasY;
elements.forEach(function(element) {
if (x > element.left && x < element.left + element.width &&
y > element.top && y < element.top + element.height) { // if rect clicked
alert('Move all cards to centre simultaneously.');
}
else if (Math.pow(x-element.arcX, 2) + Math.pow(y-element.arcY, 2) <
Math.pow(element.arcRadius, 2)) { // if circle clicked
alert('Set b1 fillColour to #FFDDB0.');
}
});
}, false);
One way is keep all element data and write a hitTest(x,y) function but when you have a lot of complex shapes its better to use a secondary canvas to render element with their ID instead of their color in it and the color of x,y in second canvas is ID of hitted element, I should mention that the second canvas is'nt visible and its just a gelper for get the hitted element.
Github Sample:
https://siamandmaroufi.github.io/CanvasElement/
Simple implementation of hitTest for Rectangles :
var Rectangle = function(id,x,y,width,height,color){
this.id = id;
this.x=x;
this.y=y;
this.width = width;
this.height = height;
this.color = color || '#7cf';
this.selected = false;
}
Rectangle.prototype.draw = function(ctx){
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.width,this.height);
if(this.selected){
ctx.strokeStyle='red';
ctx.setLineDash([5,5]);
ctx.lineWidth = 5;
ctx.strokeRect(this.x,this.y,this.width,this.height);
}
}
Rectangle.prototype.hitTest=function(x,y){
return (x >= this.x) && (x <= (this.width+this.x)) &&
(y >= this.y) && (y <= (this.height+this.y));
}
var Paint = function(el) {
this.element = el;
this.shapes = [];
}
Paint.prototype.addShape = function(shape){
this.shapes.push(shape);
}
Paint.prototype.render = function(){
//clear the canvas
this.element.width = this.element.width;
var ctx = this.element.getContext('2d');
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].draw(ctx);
}
}
Paint.prototype.setSelected = function(shape){
for(var i=0;i<this.shapes.length;i++){
this.shapes[i].selected = this.shapes[i]==shape;
}
this.render();
}
Paint.prototype.select = function(x,y){
for(var i=this.shapes.length-1;i>=0;i--){
if(this.shapes[i].hitTest(x,y)){
return this.shapes[i];
}
}
return null;
}
var el = document.getElementById('panel');
var paint = new Paint(el);
var rectA = new Rectangle('A',10,10,150,90,'yellow');
var rectB = new Rectangle('B',150,90,140,100,'green');
var rectC = new Rectangle('C',70,85,200,70,'rgba(0,0,0,.5)');
paint.addShape(rectA);
paint.addShape(rectB);
paint.addShape(rectC);
paint.render();
function panel_mouseUp(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
if(shape){
alert(shape.id);
}
//console.log('selected shape :',shape);
}
function panel_mouseMove(evt){
var p = document.getElementById('panel');
var x = evt.x - p.offsetLeft;
var y = evt.y - p.offsetTop;
var shape = paint.select(x,y);
paint.setSelected(shape);
}
el.addEventListener('mouseup',panel_mouseUp);
el.addEventListener('mousemove',panel_mouseMove);
body {background:#e6e6e6;}
#panel {
border:solid thin #ccc;
background:#fff;
margin:0 auto;
display:block;
}
<canvas id="panel" width="400px" height="200px" >
</canvas>
just click or move over the shapes

Create and position divs relative to parent

I am trying to create(and position) rectangle divs on a parent div. The created div should be positioned relative. Here is a working jsfiddle example -> Just draw some rectangles by holding mouse button.
var newRect = null;
var offset = $('#page').offset();
function point(x, y) {
this.x = x;
this.y = y;
}
function rect(firstPoint) {
this.firstPoint = firstPoint;
this.div = document.createElement("div");
this.div.style.position = "relative";
this.div.style.border = "solid 1px grey";
this.div.style.top = this.firstPoint.y+"px";
this.div.style.left = this.firstPoint.x+"px";
this.div.style.width = "0px";
this.div.style.height = "0px";
$("#page").append(this.div);
}
$("#page").mousedown(function (e) {
if(e.which == 1) {
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
newRect = new rect(new point(x, y));
}
});
$("#page").mousemove(function (e) {
if(newRect) {
newRect.div.style.width = Math.abs(newRect.firstPoint.x-(e.pageX - offset.left))+"px";
newRect.div.style.height = Math.abs(newRect.firstPoint.y-(e.pageY - offset.top))+"px";
}
});
$("#page").mouseup(function (e) {
if(e.which == 1 && newRect != null) {
if(Math.abs(newRect.firstPoint.x-(e.pageX - offset.left)) < 10) {
$("#"+newRect.div.id).remove();
newRect = null;
return;
}
$("#"+newRect.div.id).on('mousedown', function (e) {
e.stopImmediatePropagation();
});
newRect = null;
}
});
#page{
width: 210mm;
height: 297mm;
border:solid 2px #6D6D6D;
cursor: crosshair;
background-color: white;
float:left;
background-repeat: no-repeat;
background-size: contain;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page">
</div>
After drawing the first rectangle, which is positioned correctly, each rectangle is positioned false. I think that there is something wrong with the calculation of the position... maybe someone can give me a hint.
Change
this.div.style.position = "relative";
to
this.div.style.position = "absolute";
Bonus: Here's a version that allows you to draw in any direction: https://jsfiddle.net/g4z7sf5c/5/
I simply added this code to the mousemove function:
if (e.pageX < newRect.firstPoint.x) {
newRect.div.style.left = e.pageX + "px";
}
if (e.pageY < newRect.firstPoint.y) {
newRect.div.style.top = e.pageY + "px";
}

Categories