So I'm trying to get the variables x and y in the following code to determine the position of the image with the class myElement. On click it should set the top and left style to whatever the variables are (position of the cursor). When I test it out it just defaults to undefined.
<!doctype html>
<html>
<body onclick="getCoord(event)" style="height:2000px;">
<h2>click</h2>
<p id="display"></p>
<script>
function getCoord(event) {
var x = event.clientX;
var y = event.clientY;
var coord = "x:" + x + "y:" + y;
document.getElementById("display").innerHTML = coord;
console.log(x);
console.log(y);
document.getElementById('myElement').style.position = "absolute";
document.getElementById('myElement').style.top = y; //or whatever
document.getElementById('myElement').style.left = x; // or whatever]
};
</script>
<img id="myElement" src="https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364">
</body>
</html>
CSS Measurement
You had forgotten to add the measurement the numbers are to be interpreted as.
<!DOCTYPE html>
<html>
<body onclick="getCoord(event)" style="height:2000px;">
<h2>click</h2>
<p id="display"></p>
<script>
function getCoord(event) {
var x = event.clientX;
var y = event.clientY;
var coord = "x:" + x + " y:" + y;
document.getElementById("display").innerHTML = coord;
console.log(x);
console.log(y);
var myEle = document.getElementById('myElement'); // no need to use 3 times
myEle.style.position = "absolute";
myEle.style.top = y + "px"; // plus "px"
myEle.style.left = x + "px"; // plus "px"
};
</script>
<img id="myElement" src="https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364">
</body>
</html>
Related
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
I'm making an javascript image converter, just a proof of concept(I know there are another better languages for doing it). My problem is that in the loop section I'm doing some variables don't evaluate to the ones that are in the function loops. The code should work this way:
The HTML button activates the parent function.
Some variables are stated.
The loop that should make a nice gradient all over the and those I'm having trouble with are defined.
A function that triggers the loops in intervals is stated, with some other counter variables.e
I think the problem is in the counter variables I use on the loop() but I can't figure them out.
Here is all my code:
<!DOCTYPE html>
<html>
<head>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CPBitmap to PNG</title>
<style>
#canvas {
width:512px;
height:384px;
background-color:black;
}
</style>
<script>
function convertir(){
var y =0;
vertC = 10;
var pixelConverter = function(){
for(;y<vertC;y++){
for(var x=0; x<2048;x++){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var pixel = "rgb(" + y + "," + vertC + "," + x + ")";
ctx.fillStyle = pixel;
ctx.fillRect(x,y,100,100);
}
}
}
intervalos = setInterval(loops,1);
function loops(){
pixelConverter();
vertC = vertC + 10;
console.log("Y= " + y + "Linea " + vertC );
y = y + 10;
x = 0;
console.log(x);
if(x > 2047 && y > 1535)intervalos=window.clearInterval(intervalos);
else pixelConverter();
}
}
</script>
</head>
<body>
<input type="file" id="input" name="file" />
<button onclick=convertir() >¡Convertir!</button>
<button onclick="intervalos=window.clearInterval(intervalos)">Alto</button>
<canvas id="canvas" width="2048px" height="1536px"></canvas>
<div id="Hola"></div>
</body>
</html>
I'm currently working on an iOS app which uses HTML 5 and JavaScript for drawing Graphs.
I just did a sample App.
My Code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var a = 0;
var b = 0;
function init()
{
var can = document.getElementById('can');
can.addEventListener("click",click, false);
}
function click(event)
{
var can = document.getElementById('can');
var c = can.getContext('2d');
var parentPosition = getPosition(event.currentTarget);
c.lineWidth = 1;
c.strokeStyle = '#FFFFFF';
c.beginPath();
c.moveTo(a, b);
a = event.clientX - parentPosition.x;
b = event.clientY - parentPosition.y;
c.lineTo(a, b);
c.stroke();
}
function getPosition(element)
{
var xPosition = 0;
var yPosition = 0;
while (element)
{
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
</script>
</head>
<body oncopy='copy();' onpaste='paste();'onload ='init();'>
<canvas id="can" style="height:300px;width:300px;background-color:black;">Oops!</canvas>
</body>
</html>
My Issue:
When a user Taps on the screen, I'm drawing a line to that particular point from previous point.
But in my case when I tap on the screen the line is drawn to some other point. Say if I tapped on point (100,100) the line will be drawn to (100, some arbitrary value). Always the Y position is wrong.
What I did:
Tested it on simulator
Tested it on device
Tested it on Firefox
Tested it on Chrome
All results are same. I couldn't find the issue. I alerted the clicked x and y co-ordinate. It's coming correctly. Only problem is with the draw functionality.
Screenshots:
As you can see the X-coordinate is correct. But Y-coordinate is always coming wrong.
Please help me, Thanks in advance.
Can you please make these changes.
In html line#47,
<canvas id="can" height=300 width=300 style="background-color:red;">Oops!</canvas>
In script line#23,
c.beginPath();
c.moveTo(a, b);
a = event.clientX - parentPosition.x;
b = event.clientY - parentPosition.y;
console.log('a:'+a+'--b:'+b);
c.lineTo(a, b);
c.stroke();
TO CLEAR
This is the code that you have to change to have a reusable code:
c.moveTo(a/(can.clientWidth/can.width), b/(can.clientHeight/can.height));
a = event.clientX - parentPosition.x;
b = event.clientY - parentPosition.y;
console.log('a:'+a+'--b:'+b);
c.lineTo(a/(can.clientWidth/can.width), b/(can.clientHeight/can.height));
If you don't use this, the code below works only for 300x300 canvas size.
LAST EDIT:
By analyzing the 2d context (var c = can.getContext('2d');console.log(c);) you can easily understand this error: there is a relation (not explicit) from the canvas and it's 2d context.
As you can see from the image:
the height and the width of the canvas(this is 500*500) are differents from its offset,scroll and client size. So, before to draw, you need to calculate the ratio: 500/150 will be the height coefficient and 500/300 the width one, so a will be multiplied by 1.66667 and b will be multiplied by 3.33333.
Same for the old example (canvas 300*300) the coefficent are 300/300=1 (a:width) 300/150=2 (b:height)
OLD REPLY:
But now, you have to guess why..cause actually I have no time
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
var a = 0;
var b = 0;
function init()
{
var can = document.getElementById('can');
can.addEventListener("click",click, false);
}
function click(event)
{
var can = document.getElementById('can');
var c = can.getContext('2d');
var parentPosition = getPosition(event.currentTarget);
console.log(parentPosition);
console.log(event);
c.lineWidth = 1;
c.strokeStyle = '#FFFFFF';
c.beginPath();
c.moveTo(a, b/2);
a = event.clientX - parentPosition.x;
b = event.clientY - parentPosition.y;
console.log('a:'+a+'--b:'+b);
c.lineTo(a, b/2);
c.stroke();
}
function getPosition(element)
{
var xPosition = 0;
var yPosition = 0;
while (element)
{
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
</script>
</head>
<body oncopy='copy();' onpaste='paste();'onload ='init();'>
<canvas id="can" style="height:300px;width:300px;background-color:black;">Oops!</canvas>
<br>
pagex<input type="text" id="ics">pagey<input type="text" id="ips"><br>
screenx<input type="text" id="ics2">screeny<input type="text" id="ips2">
<script>
$("#can").mousemove(function(event) {
var msg = "Handler for .mousemove() called at ";
document.getElementById('ics').value= event.pageX
document.getElementById('ips').value= event.pageY;
document.getElementById('ics2').value= event.screenX;
document.getElementById('ips2').value= event.screenY;
});
</script>
</body>
</html>
Currently I'm creating a sheet of graph paper with the canvas object in HTML5. I'm able to create the canvas as well as fill in the selected areas with a color by finding the x/y position. Unfortunately I'm having some troubles using the jQuery mousemove method to display a pop-up of the information selected for the square.
Here's my code:
Canvas Creation/Layout:<br>
<script type="text/javascript">
var canvas;
var context;
var color;
var state;
var formElement;
var number = 0;
function showGrid()
{
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
context.lineWidth=0.5;
context.strokeStyle='#999999';
lineSpacing=10;
var xPos = 0;
var yPos = 0;
var numHorizontalLines = parseInt(canvas.height/lineSpacing);
var numVerticalLines = parseInt(canvas.width/lineSpacing);
state = new Array(numHorizontalLines);
for (var y = 0; y < numHorizontalLines; ++y)
{
state[y] = new Array(numVerticalLines);
}
for(var i=1; i<=numHorizontalLines;i++)
{
yPos=i*lineSpacing;
context.moveTo(0,yPos);
context.lineTo(canvas.width,yPos);
context.stroke;
}
for(var i=1; i<=numVerticalLines; i++)
{
xPos=i*lineSpacing;
context.moveTo(xPos,0);
context.lineTo(xPos,canvas.height);
context.stroke();
}
}
function fill(s, gx, gy)
{
context.fillStyle = s;
context.fillRect(gx * lineSpacing, gy * lineSpacing, lineSpacing, lineSpacing);
if(s != null)
{
}
}
function getPosition(e)
{
var x = new Number();
var y = new Number();
var canvas = document.getElementById("canvas");
if (e.pageX || e.pageY)
{
x = e.pageX;
y = e.pageY;
}
else
{
x = e.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
var gx = Math.floor((x / lineSpacing));
var gy = Math.floor((y / lineSpacing));
state[gy][gx] = true;
fill(color, gx, gy);
addNumber();
}
HTML:
<div class="graphpaper" id="graphpaper" onclick="getPosition(event)" style="width:956px; height:1186px;">
<img src="images/PosterBorder_Top.png" align="right"/>
<img src="images/posterBorder_left.png" align="left" valign="top"/>
<canvas id ="canvas" width = "920" height = "1160" align="left">
</canvas>
</div>
<!-- HIDDEN / POP-UP DIV -->
<div id="pop-up">
<h3>Pop-up div Successfully Displayed</h3>
<p>
This div only appears when the trigger link is hovered over.
Otherwise it is hidden from view.
</p>
</div>
jQuery for Pop-Up display:
$('#canvas').mousemove(function(event){
console.log("Here I am!");
$('div#pop-up').show().appendTo('body');
});
Any suggestions? I'm obviously missing something but from what I've done this should work I believe.
<!DOCTYPE html>
<html>
<head>
<meta lang="EN" />
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// Don't resize the window
function _(str){
return document.getElementById(str);
}
function incPixel(imageData, x, y){
var index = (x + y * imageData.width) * 4;
imageData.data[index + 0] = 155;
imageData.data[index + 1] = 155;
imageData.data[index + 2] = 155;
imageData.data[index + 3] = 155;
}
$(document).ready(function(){
// collect mouse position data
var history = [];
$(document).mousemove(function(e){
history.push([e.pageX, e.pageY]);
});
// when the button is clicked
$("#button").click(function(){
// 1. disable mouse position data collection
$(document).unbind("mousemove");
// 2. draw pixels on the canvas
var width = $(document).width();
var height = $(document).height();
$("#canvas").height(height).width(width);
var canvas = document.getElementById("canvas");
if(canvas.getContext){
var context = canvas.getContext("2d");
var imageData = context.createImageData(width, height);
for(var i=0; i<history.length; i++){
incPixel(imageData, history[i][0], history[i][1]);
}
context.putImageData(imageData, 0, 0);
alert(JSON.stringify(history));
}else{
alert("no context");
}
});
});
</script>
</head>
<body>
<h1>Hello, Worlds!</h1>
<div id="width"></div>
<div id="height"></div>
<input type="button" id="button" value="Click me" /><br />
<canvas id="canvas" />
</body>
</html>
You're missing the context type parameter from getContext(), it should be:
var context = canvas.getContext('2d');
You can test out a demo here with only the change above.