Get Click Coordinates on canvas inside DIV - javascript

I have a canvas inside a div which makes it scrollable to the right/left if its to large. I need to get the click coordinates on the canvas. I have tried so many different things I have seen but nothing is giving me the right coordinates. I have a rectangle in the canvas and when i click on the rectangle which is at a set coordinate.The "clicked" coordinates are not what they should be the x coordinate is 100px short. Could anyone point me in the right direction ?
HTML:
<div id="cv">
<canvas id="canvas" width="30000" height="600"></canvas>
</div>
CSS:
<style>
#cv{
display: block;
width: 1500px;
height: 500px;
overflow: auto;
}
<script>
canvas.addEventListener("mousedown", doMouseDown, false);
function doMouseDown(event){
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do{
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while(currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
}
</script>

I just used a mouse following function, and if there was a click it takes the coordinates of that. It isnt how I wanted it to go but it seems to be working fine.

Related

Zoom in picture on hover using javascript

I'm new with JS.
https://codepen.io/Maartinshh/pen/VbGOvm
Here's my code:
html
<img id="imgZoom" width="200px" height="200px" onmousemove="zoomIn(event)" onmouseout="zoomOut()" src="https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAA20AAAAJDZhZjAwOTE3LTExMDQtNDE5OC05NDdhLWUxYTU0ODJiZTdkYQ.png">
<div id="overlay" onmousemove="zoomIn(event)"></div>
css
#overlay {
border: 1px solid black;
width: 450px;
height: 450px;
position: absolute;
display: inline-block;
background-image: url('https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAA20AAAAJDZhZjAwOTE3LTExMDQtNDE5OC05NDdhLWUxYTU0ODJiZTdkYQ.png');
background-repeat: no-repeat;
}
js
function zoomIn(event) {
var element = document.getElementById("overlay");
element.style.display = "inline-block";
var img = document.getElementById("imgZoom");
var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
element.style.backgroundPosition = (-posX * 1) + "px " + (-posY * 1) + "px";
}
function zoomOut() {
var element = document.getElementById("overlay");
element.style.display = "none";
}
Problem that occurs: If you see, then when I mouseover picture on left side, the right side (zoomed) picture, doesn't really follow correctly with zoom. What am I doing wrong?
Also, how can I change zoom level (zoom closer)?
Thanks in advance.
You need to do some calculations to add extra offset to place img at center of the div
var offY = (element.clientHeight -img.clientHeight)/2;
var offX = (element.clientWidth -img.clientWidth)/2;
edited codepen here

How to transfer events into the canvas { pointer-events : none }; (!in KonvaJS)

The essence of the title is described and presented in my example.
My task is to make the pseudo shape. You need to hover on the canvas element (triangle), canvas accepted property {pointer-events:all}, and the care with this element {pointer-events:none}. How this can be done using the framework konvajs.
/*NON GIST*/
var stage=new Konva.Stage({container:'container',width:300,height:300})
,layer=new Konva.Layer()
,triangle=new Konva.RegularPolygon({x:80,y:120,sides:3,radius:80,fill:'#00D2FF',stroke:'black',strokeWidth:4})
,text=new Konva.Text({x:10,y:10,fontFamily:'Calibri',fontSize:24,text:'',fill:'black'});
function writeMessage(message){text.setText(message);layer.draw();}
/*GIST*/
triangle.on('mouseout', function() {
$('#container').css('pointer-events',/*!*/'none');
writeMessage('Mouseout triangle');
});
/*! How do I know if the events are not tracked on the canvas?*/
triangle.on('mousemove', function() {
$('#container').css('pointer-events',/*!*/'all');
var mousePos = stage.getPointerPosition();
var x = mousePos.x - 190;
var y = mousePos.y - 40;
writeMessage('x: ' + x + ', y: ' + y);
});
/*/GIST/*/
layer.add(triangle);
layer.add(text);
stage.add(layer);
body{
margin: 0;
padding: 0;
overflow: hidden;
background-color: #F0F0F0;}
#container{
position:absolute;
z-index:1;
}
.lower-dom-element{
position:absolute;
z-index:0;
padding:20px;
background:#0e0;
top: 90px;
left: 0px;}
<script src="https://cdn.rawgit.com/konvajs/konva/0.9.0/konva.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id="container"></div>
<div class="lower-dom-element">
If the POINTER-EVENTS on me, then canvas POINTER-EVENTS:NONE, and vice versa.
If the events are not on the triangle, then the event with me.
</div>
PS: sorry for my english.
var $con = $('#container');
$(document.body).mousemove(function(event) {
var x = event.clientX, y = event.clientY;
var offset = $con.offset();
// manually check intersection
if (layer.getIntersection({x: x - offset.left, y: y - offset.top})){
$con.css('pointer-events',/*!*/'all');
} else {
$con.css('pointer-events',/*!*/'none');
}
});
Demo: http://jsfiddle.net/vfp22dye/3/

Javascript paint canvas

I have a problem with my code. It is a simple canvas element drawing circles. There are two things I cannot figure out. The first one is how to draw circles continously (not one at a time) while I keep left mouse button pressed. "Onmousehold" doesn't seem to work here. Secondly is it possible to get rid of the first reference error from the console? It appears only once when coordinates of a click are not yet specified. My code here:
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
}
outer.addEventListener("click",getMousePos);
outer.addEventListener("click",showBox);
outer.addEventListener("mousedown",showBox);
#outer {
position:relative;
overflow: hidden;
border: 1px solid green;
}
.popup {
width: 50px;
height: 50px;
border-radius: 25px;
background-color: blue;
position: absolute;
}
<canvas id="outer" width="600" height="600">
</canvas>
And jsfiddle
jsfiddle
see this: http://jsfiddle.net/4ovgzk07/2/
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
outer.addEventListener("mousemove",getMousePos);
outer.addEventListener("mousemove",showBox)
outer.addEventListener("mouseup",removelisteners);
}
function removelisteners() {
outer.removeEventListener("mousemove",getMousePos);
outer.removeEventListener("mousemove",showBox)
}
outer.addEventListener("mousedown",getMousePos);
outer.addEventListener("mousedown",showBox);
;
Youu need to attach events for mousemove when mousedown occurs, similarly remove those events on mouseup

Making a 'div' go in a circle

I am working on a bit of code to have a dot circle around your cursor on a webpage, but I am having trouble getting the 'div' to follow the path I want; in fact, the object is not moving at all and I cannot figure out why my code does not work. Here is the code that is causing me trouble from what I've narrowed down:
<!DOCTYPE HTML>
<head>
<title>TEST SPACE</title>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="test"></div>
<style>
#test {
background-color: black;
height: 10px;
width: 10px;
border-radius: 100%;
position: absolute;
top: 50%;
left: 50%;
}
</style>
<script>
const omega = Math.PI / 2000;
function dotRotation() {
var time = 0;
var x = 20*(Math.sin(omega*time));
var y = 20*(Math.cos(omega*time));
document.getElementById("test").style.marginLeft = x;
document.getElementById("test").style.marginTop = y;
time += 25;
};
$(document).ready(function() {
setInterval('dotRotation()',25);
});
</script>
</body>
JSFiddle
Two things are wrong
You need to move your time variable outside of the function
You need to give a unit to the value you pass to the margins so add +'px' after the variables .marginTop = y + 'px';
So altogether
const omega = Math.PI / 2000;
var time = 0;
function dotRotation() {
var x = 20*(Math.sin(omega*time));
var y = 20*(Math.cos(omega*time));
var style = document.getElementById("test").style;
style.marginLeft = x +'px';
style.marginTop = y +'px';
time += 25;
};
Demo at http://jsfiddle.net/mWC63/
Also you can cache references to the dom to avoid the searching
Your fiddle is set to run onload, it should be set up to run in the head. [drop down on left under jQuery selection.]
time is declared inside of the function so it is reset back to zero every single time it is called. Move it outside of dotRotation
var time = 0;
function dotRotation() {
var x = 20*(Math.sin(omega*time));
var y = 20*(Math.cos(omega*time));
$("#test").css({"marginLeft" : x + "px", "marginTop" : y + "px"});
time += 25;
};
$(function() {
setInterval(dotRotation,25);
});

javascript mouse coordinates with canvas and css

well right now im trying to learn how to use the canvas tag on html, and im having trouble handling mouse events when i apply css to the document.
the issue starts when i move the div containing the canvas and center it on the page, the first poing of the canvas wouldnt be 0 because its centered and for some reason 0,0 would be the beginning of the screen and not the beginning of the canvas, which i found weird because im adding the event listener to the canvas directly.
here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<style type="text/css">
body {
font: 100%/1.4 Verdana, Arial, Helvetica, sans-serif;
background: #42413C;
margin: 0;
padding: 0;
color: #000;
}
#divId {
width: 800px;
height: 600px;
text-align:center;
margin: 20px auto;
background-color:#0099FF;
}
</style>
<script>
window.onload = function () {
var canvas = document.getElementById('canvasId');
var c = canvas.getContext('2d');
alert("lol");
canvas.addEventListener('mousedown', hmd, false);
function hmd(e) {
alert ("x: " + e.clientX + " y: " + e.clientY);
}
}
</script>
</head>
<body>
<div id="divId">
<canvas height="300" width="800" id="canvasId" />
</div>
</body>
</html>
so i read somewhere that the issue was caused by the div, but when i tried to give css directly to the canvas tag it didnt work, so basically what i need to do, is to get that canvas centered or placed anywhere on the screen, but having its first pixel as 0,0.
adding a solution would be hard because its centering automatically, so i would need to know the user resolution to be able to calculate the offset so what im looking for is a way to do it simply with css or something.
To get the coordinates relatively to the canvas, do this:
function hmd(e) {
var rx = e.pageX, ry = e.pageY;
rx -= canvas.offsetLeft;
ry -= canvas.offsetTop;
alert ("x: " + rx + " y: " + ry);
}
This assumes your canvas variable definition is global.
Edit: another method:
function hmd(e) {
var rx, ry;
if(e.offsetX) {
rx = e.offsetX;
ry = e.offsetY;
}
else if(e.layerX) {
rx = e.layerX;
ry = e.layerY;
}
}
Here's what I've been using for my latest experimentation. It works with damn near everything: Borders, paddings, position:fixed elements offsetting the HTML element, etc. It also works on all touch devices and even if the browser is zoomed.
http://jsfiddle.net/simonsarris/te8GQ/5/
var stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingLeft'], 10) || 0;
var stylePaddingTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['paddingTop'], 10) || 0;
var styleBorderLeft = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderLeftWidth'], 10) || 0;
var styleBorderTop = parseInt(document.defaultView.getComputedStyle(can, undefined)['borderTopWidth'], 10) || 0;
var html = document.body.parentNode;
var htmlTop = html.offsetTop;
var htmlLeft = html.offsetLeft;
function getMouse(e) {
var element = can,
offsetX = 0,
offsetY = 0,
mx, my;
// Compute the total offset
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar
offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
offsetY += stylePaddingTop + styleBorderTop + htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object (a hash) with x and y defined
return {
x: mx,
y: my
};
}

Categories