setInterval not clearing on mouseover - javascript

So I have 2 problems. first is the clearInterval does not seem to be working as the image continues to rotate when the mouse cursor is over the image. second is the rightDisc is the setInterval seems to not work on the rightDisc. all the other functions do work. I tried looking into threading with web workers but that's all sorts of confusing me.
<html>
<head>
<script src="../js/jquery-1.6.4.min.js"></script>
<script src="../js/imgRotate.js"></script>
<script>
$(function()
{
$("#leftDisc").rotate();
$("#rightDisc").rotate();
});
</script>
</head>
<body>
<div>
<img id="turnTableImage" src="turntable.jpg" height="400" width="600" alt="" />
</div>
<div id="leftDisc" style="margin-top: -280px; margin-left: 50px">
left<img id="leftDiscImg" class="discs" height="200" src="disc.png" alt="" />
</div>
<div id="rightDisc" style="margin-top: -300px; margin-left: 350px">
<img id="rightDiscImg" class="discs" src="disc.png" alt="" />right
</div>
</body>
imgRotate.js
(function($) {
$.fn.rotate = function() {
var img = this.find(".discs");
var imgpos = img.position();
var x, y, xCenter, yCenter, x1, y1, deg = 1, drag = false;
var interval = setInterval(function() {
deg++;
$("#leftDiscImg").css("transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-moz-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-webkit-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-o-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("ms-transform","rotate("+deg+"deg)");
}, 20);
$(window).load(function() {
img.removeAttr("width");
img.removeAttr("height");
xCenter = imgpos.left + (img.width() / 2);
yCenter = imgpos.top + (img.height() / 2);
});
img.mousemove(function(e) {
x1 = e.pageX;
y1 = e.pageY;
x = x1 - xCenter;
y = y1 - yCenter;
r = 360 - ((180/Math.PI) * Math.atan2(y,x));
if (drag == true) {
img.css("transform","rotate(-"+r+"deg)");
img.css("-moz-transform","rotate(-"+r+"deg)");
img.css("-webkit-transform","rotate(-"+r+"deg)");
img.css("-o-transform","rotate(-"+r+"deg)");
img.css("ms-transform","rotate(-"+r+"deg)");
}
});
img.mouseover(function() {
clearInterval(interval);
deg = 1;
if (drag == false) {
drag = true;
} else {
drag = false;
}
});
img.mouseout(function() {
drag = false;
interval = setInterval(function() {
deg++;
$("#leftDiscImg").css("transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-moz-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-webkit-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("-o-transform","rotate("+deg+"deg)");
$("#leftDiscImg").css("ms-transform","rotate("+deg+"deg)");
}, 20);
});
};
})( jQuery );

Related

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

Make a picture as a link

How can I make an image in a canvas to act as a link?
I am not able to put < a href > tag on the < image > tag as I dont want it to be displayed first until the user click on a button.
Is there any line of code I need to insert in the javascript?
window.onload = function () {
var endCan = document.getElementById("endCan");
var end = endCan.getContext("2d");
var img = document.getElementById("end");
end.drawImage(img, 0, 0, img.width / 2, img.height / 2);
};
<img id="end" style="display: none;" src="img/WellDone_Rectangle.png"/>
<canvas id="endCan" class="wrapper" width="1000" height="600"></canvas>
$(".buttonNext6").click(function () {
$("#endCan").fadeIn();
});
You need to add a click event handler to the canvas, and then when it's clicked you check the co-ordinates to see if it was clicked where your image was drawn.
Here's an example, using a rectangle drawn on a canvas...
var endCan = document.getElementById("endCan");
var endCtx = endCan.getContext("2d");
endCtx.rect(10, 20, 150, 100);
endCtx.fill();
endCan.addEventListener("click", function(e) {
if (e.clientX >= 10 && e.clientX <= 160 &&
e.clientY >= 20 && e.clientY <= 120) {
alert("clicked");
}
});
<canvas id="endCan" class="wrapper" width="500" height="300"></canvas>
window.onload = function () {
var endCan = document.getElementById("endCan");
var end = endCan.getContext("2d");
var img = document.getElementById("end");
end.drawImage(img, 0, 0, img.width / 2, img.height / 2);
};
//$(".buttonNext6").click(function () {
// $("#endCan").fadeIn();
//});
function canvasCallback() {
console.log('clicked')
}
<img id="end" style="display: none;" src="https://picsum.photos/200/300"/>
<canvas onclick="canvasCallback()" id="endCan" class="wrapper" width="1000" height="600"></canvas>

Returning size images zoom in zoom out

I want to zoom in and out of the section image with my fingers and then return to the original image size again.
Currently, after the image is enlarged, the image will not come back to the original.
The desired order list.
1. Zoom in and out of the image -> ok
2. Resize the image back to its original size. -> fail
3. Center the coordinates of the image -> fail
var canvas;
var gMarginWidth = 0;
var gMarginHeight = 0;
var gImageWidth = 0;
var gRatio = 0;
$(document).ready(function() {
canvas_result();
});
function canvas_result(){
//canvas
canvas = new fabric.Canvas('c',
{
selection : false,
controlsAboveOverlay:true,
centeredScaling:true,
allowTouchScrolling: false
}
);
gRatio = 0;
gMarginWidth = 0;
gMarginHeight = 0;
function resizeCanvas(imageWidth) {
canvas.setHeight(window.innerHeight*0.5);
canvas.setWidth(imageWidth);
canvas.renderAll();
}
fabric.Image.fromURL("http://59.25.178.93:8080/homesys/rest/testservice/0/imgLoadAdm.do?fileId=HF201801221742200845&fileSn=2", function(img) {
var xRatio = $('#canvasWrapper').width()/img.width;
var yRatio = (window.innerHeight*0.5)/img.height;
gRatio = xRatio < yRatio ? xRatio : yRatio;//길이에 맞게 조절할 배율
gImageWidth = img.width * gRatio;
gMarginWidth = ($('#canvasWrapper').width() - img.width * gRatio) / 2;
gMarginHeight = (600- img.height * gRatio)/2;
resizeCanvas($('#canvasWrapper').width());
canvas.setBackgroundImage(img);
canvas.setZoom(gRatio);//평면도 가로 길이가 canvas에 꽉 차도록 zoom
canvas.renderAll();
});
//캔버스 마우스 클릭 이벤트
canvas.on({
'mouse:up': function(event) {
self.canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), 0.305);
},
//캔버스 터치 이벤트 확대, 축소
'touch:gesture': function(event) {
// Handle zoom only if 2 fingers are touching the screen
if (event.e.touches && event.e.touches.length == 2) {
// Get event point
var point = new fabric.Point(event.self.x, event.self.y);
// Remember canvas scale at gesture start
if (event.self.state == "start") {
zoomStartScale = self.canvas.getZoom();
}
var delta = zoomStartScale * event.self.scale ;
// Zoom to pinch point
// self.canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), delta);
self.canvas.zoomToPoint(point, delta);
}
}
});
}
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="card" style="background-color: #fff;">
<label style="margin-bottom:5px; margin-top:25px;">
<font size="3" style="margin-left: 10px">Zoom in/ out</font>
<font id="clocks" style="margin-left: 10px" size="1"></font>
</label>
<hr class="style1" style="margin-bottom: 20px; margin-left: 30px; margin-right: 30px; margin-top: 0px;">
<div id="canvasWrapper">
<canvas class="img-responsive img-rounded" id="c"></canvas>
</div>
</div>
snippet ok
https://jsfiddle.net/6kjL3xe4/6/
I solved the answer to my question.
The correct answer is console.log (self.canvas); Respectively.
And the viewportTransform found there is my gem.
'mouse:up': function(event) { [zoomStartScale,0,0,zoomStartScale,0,0];
},
//캔버스 터치 이벤트 확대, 축소
'touch:gesture': function(event) {
// Handle zoom only if 2 fingers are touching the screen
if (event.e.touches && event.e.touches.length == 2) {
// Get event point
var point = new fabric.Point(event.self.x, event.self.y);
//point_x = -1 * event.self.x;
//point_y = -1 * event.self.y;
// Remember canvas scale at gesture start
if (event.self.state == "start") {
zoomStartScale = self.canvas.getZoom();
}
var delta = zoomStartScale * event.self.scale ;
// Zoom to pinch point
// self.canvas.zoomToPoint(new fabric.Point(canvas.width / 2, canvas.height / 2), delta);
self.canvas.zoomToPoint(point, delta);
}
}
});

How to add tooltip on draggable objects within Canvas?

In my code SVG is parse and drawn on Canvas and also orange1.png and green1.png images are plotted on SVg file. In this I am able to zoom and Pan canvas and also able to drag images which are plotted on it through JSON.
Now I want to add tooltip on the images (orange1.png and green1.png) When I click on those images or mouseover on those images.
showTooltip function is for showing the tooltip on those images(orange1.png , green1.png).
clearTooltip function is for clearing the tooltip.
Where and how should I add showTooltip and clearTooltip function in my updated code?
And which option will be better mouse click or mosehover for showing tooltip?
I tried some possibilities but I am missing something.
function showTooltip(x, y, index) {
var editedValue = [];
if (tooltip === null) {
tooltip = document.createElement('div');
tooltip.className = 'tooltip';
tooltip.style.left = (x) + 'px';
tooltip.style.top = (y) + 'px';
tooltip.innerHTML = "<input type='text' id='generic_txt' value='"+dataJSON[index].tooltiptxt[0]+"' /> <input type='submit' id='generic_edit' value='Edit'>"
document.getElementsByTagName('body')[0].appendChild(tooltip);
}
document.getElementById('generic_txt').setAttribute('disabled', 'disabled');
$("#generic_edit").click(function(){
if(document.getElementById('generic_edit').value == "Edit"){
document.getElementById('generic_txt').removeAttribute('disabled');
document.getElementById('generic_txt').focus();
document.getElementById('generic_edit').value = "Change";
} else {
document.getElementById('generic_txt').setAttribute('disabled', 'disabled');
document.getElementById('generic_edit').value = "Edit";
editedValue = $('#generic_txt').val();
dataJSON[index].tooltiptxt[0] = editedValue; // important line
}
return false;
});
}
function clearTooltip(doFade) {
if (tooltip !== null) {
var fade = 1;
function fadeOut() {
tooltip.style.opacity = fade;
fade -= 0.1;
if (fade > 0) {
setTimeout(fadeOut, 16);
} else {
remove();
}
}
function remove() {
document.getElementsByTagName('body')[0].removeChild(tooltip);
tooltip = null;
}
if (doFade === true) {
fadeOut();
//$('.first_cancel').click(fadeOut());
} else {
remove();
}
}
}
Following is my updated source code.
HTML Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<style>
canvas {
border:1px solid #000
}
.tooltip{
*position:fixed;
position:absolute;
*background:#ff7;
background:green;
border:1px solid #000;
padding:7px;
font-family:sans-serif;
font-size:12px;
}
.tooltip2 {
*position:fixed;
position:absolute;
background:pink;
border:1px solid #000;
padding:7px;
font-family:sans-serif;
font-size:12px;
}
</style>
</head>
<body>
<script src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<canvas id="myCanvas" width="800" height="700" style="border: 1px solid;margin-top: 10px;"></canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+">
<input type="button" id="minus" value="-">
<input type="button" id="original_size" value="100%">
</div>
<script src="/static/js/markers.js"></script>
<script src="/static/js/draw.js"></script>
</body>
</html>
draw.js:
var dataJSON = data || [];
var dataJSON2 = data2 || [];
window.onload = function(){
//$(function(){
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#myCanvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var lastX=0;
var lastY=0;
var panX=0;
var panY=0;
var dragging=[];
var dragging2=[];
var isDown=false;
function loadImages(sources, callback){
var images = {};
var loadImages = 0;
var numImages = 0;
//get num of sources
for(var i in sources){
numImages++;
}
for(var i in sources){
images[i] = new Image();
images[i].onload = function(){
if(++loadImages >= numImages){
callback(images);
}
};
images[i].src = sources[i];
}
}
var sources = {orange : '/static/images/orange1.png', green : '/static/images/green1.png'};
// load the tiger image
var svgfiles = ["/static/images/awesome_tiger.svg"];
/*var tiger=new Image();
tiger.onload=function(){
draw();
}
tiger.src="tiger.png";*/
function draw(scaleValue){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.drawSvg(svgfiles[0],panX,panY,400*scaleValue, 400*scaleValue);
//ctx.drawImage(tiger,panX,panY,tiger.width,tiger.height);
//ctx.scale(scaleValue, scaleValue);
loadImages(sources, function(images){
ctx.scale(scaleValue, scaleValue);
for(var i = 0, pos; pos = dataJSON[i]; i++) {
ctx.drawImage(images.orange, parseInt(parseInt(pos.x) + parseInt(panX / scaleValue)), parseInt(parseInt(pos.y) + parseInt(panY / scaleValue)), 20/scaleValue, 20/scaleValue);
}
for(var i = 0, pos; pos = dataJSON2[i]; i++) {
ctx.drawImage(images.green, parseInt(parseInt(pos.x) + parseInt(panX / scaleValue)), parseInt(parseInt(pos.y) + parseInt(panY / scaleValue)), 20/scaleValue, 20/scaleValue);
}
ctx.restore();
});
};
var scaleValue = 1;
var scaleMultiplier = 0.8;
draw(scaleValue);
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function(){
scaleValue /= scaleMultiplier;
//checkboxZoomPan();
draw(scaleValue);
}, false);
document.getElementById("minus").addEventListener("click", function(){
scaleValue *= scaleMultiplier;
//checkboxZoomPan();
draw(scaleValue);
}, false);
document.getElementById("original_size").addEventListener("click", function(){
scaleValue = 1;
//checkboxZoomPan();
draw(scaleValue);
}, false);
// create an array of any "hit" colored-images
function imagesHitTests(x,y){
// adjust for panning
x-=panX;
y-=panY;
// create var to hold any hits
var hits=[];
// hit-test each image
// add hits to hits[]
loadImages(sources, function(images){
for(var i = 0, pos; pos = dataJSON[i]; i++) {
if(x >= parseInt(pos.x * scaleValue) && x <= parseInt((pos.x * scaleValue) + 20) && y >= parseInt(pos.y * scaleValue) && y <= parseInt((pos.y * scaleValue) + 20)){
hits.push(i);
}
}
});
return(hits);
}
function imagesHitTests2(x,y){
// adjust for panning
//x-=panX;
//x = parseInt(x) - parseInt(panX);
// y-=panY;
x-=panX;
y-=panY;
// create var to hold any hits
var hits2=[];
// hit-test each image
// add hits to hits[]
loadImages(sources, function(images){
for(var i = 0, pos; pos = dataJSON2[i]; i++) {
//if(x > pos.x && x < parseInt(parseInt(pos.x) + parseInt(20)) && y > pos.y && y < parseInt(parseInt(pos.y) + parseInt(20))){
if(x >= parseInt(pos.x * scaleValue) && x <= parseInt((pos.x * scaleValue) + 20) && y >= parseInt(pos.y * scaleValue) && y <= parseInt((pos.y * scaleValue) + 20)){
hits2.push(i);
}
}
});
return(hits2);
}
function handleMouseDown(e){
// get mouse coordinates
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// set the starting drag position
lastX=mouseX;
lastY=mouseY;
// test if we're over any of the images
dragging=imagesHitTests(mouseX,mouseY);
dragging2=imagesHitTests2(mouseX,mouseY);
// set the dragging flag
isDown=true;
}
function handleMouseUp(e){
// clear the dragging flag
isDown=false;
}
function handleMouseMove(e){
// if we're not dragging, exit
if(!isDown){
return;
}
//get mouse coordinates
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// calc how much the mouse has moved since we were last here
var dx=mouseX-lastX;
var dy=mouseY-lastY;
// set the lastXY for next time we're here
lastX=mouseX;
lastY=mouseY;
// handle drags/pans
if(dragging.length>0){
// we're dragging images
// move all affected images by how much the mouse has moved
for(var i = 0, pos; pos = dataJSON[dragging[i]]; i++) {
pos.x = parseInt(pos.x) + parseInt(dx);
pos.y = parseInt(pos.y) + parseInt(dy);
}
}
else if(dragging2.length>0){
for(var i = 0, pos1; pos1 = dataJSON2[dragging2[i]]; i++) {
pos1.x = parseInt(pos1.x) + parseInt(dx);
pos1.y = parseInt(pos1.y) + parseInt(dy);
}
}
else{
// we're panning the tiger
// set the panXY by how much the mouse has moved
panX+=dx;
panY+=dy;
}
draw(scaleValue);
}
// use jQuery to handle mouse events
$("#myCanvas").mousedown(function(e){handleMouseDown(e);});
$("#myCanvas").mousemove(function(e){handleMouseMove(e);});
$("#myCanvas").mouseup(function(e){handleMouseUp(e);});
// }); // end $(function(){});
}
markers.js:
data = [
{ "id" :["first"],
"x": ["195"],
"y": ["150"],
"tooltiptxt": ["Region 1"]
},
{
"id" :["second"],
"x": ["255"],
"y": ["180"],
"tooltiptxt": ["Region 2"]
},
{
"id" :["third"],
"x": ["200"],
"y": ["240"],
"tooltiptxt": ["Region 3"]
}
];
data2 = [
{ "id" :["first2"],
"x": ["225"],
"y": ["150"],
"tooltiptxt": ["Region 21"]
},
{
"id" :["second2"],
"x": ["275"],
"y": ["180"],
"tooltiptxt": ["Region 22"]
},
{
"id" :["third3"],
"x": ["300"],
"y": ["240"],
"tooltiptxt": ["Region 23"]
}
];
I think you can try out this :
<!DOCTYPE html>
<html>
<head>
<title>Canvas Links Example</title>
<script>
function OnLoad(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.translate(0.5, 0.5);
ctx.strokeStyle = "#5F7FA2";
ctx.strokeRect(50, 50, 25, 25);
var img = new Image();
img.src = "http://www.cs.washington.edu/education/courses/csep576/05wi/projects/project4/web/artifact/liebling/average_face.gif";
var img1 = new Image();
img1.src = "E:\Very IMP Projects\WinService\SourceCode\MVC\BpmPresentation\Images\loading.gif";
img.onload = function(){
ctx.drawImage(img, 50, 50);
canvas.addEventListener("mousemove", on_mousemove, false);
canvas.addEventListener("click", on_click, false);
Links.push(50 + ";" + 50 + ";" + 25 + ";" + 25 + ";" + "http://plus.google.com/");
}
var Links = new Array();
var hoverLink = "";
var canvas1 = document.getElementById("myCanvas1");
var ctx1 = canvas1.getContext("2d");
function on_mousemove (ev) {
var x, y;
if (ev.layerX || ev.layerX == 0) { // For Firefox
x = ev.layerX;
y = ev.layerY;
}
for (var i = Links.length - 1; i >= 0; i--) {
var params = new Array();
params = Links[i].split(";");
var linkX = parseInt(params[0]),
linkY = parseInt(params[1]),
linkWidth = parseInt(params[2]),
linkHeight = parseInt(params[3]),
linkHref = params[4];
if (x >= linkX && x <= (linkX + linkWidth) && y >= linkY && y <= (linkY + linkHeight)){
document.body.style.cursor = "pointer";
hoverLink = linkHref;
ctx1.translate(0.5, 0.5);
ctx1.strokeStyle = "#5F7FA2";
canvas1.style.left = x + "px";
canvas1.style.top = (y+40) + "px";
ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
var img1 = new Image();
img1.src = "E:\Very IMP Projects\WinService\SourceCode\MVC\BpmPresentation\Images\loading.gif";
img1.onload = function () {
ctx1.drawImage(img1, 50, 50);
}
break;
}
else {
document.body.style.cursor = "";
hoverLink = "";
canvas1.style.left = "-200px";
}
};
}
function on_click(e) {
if (hoverLink) {
window.open(hoverLink);
//window.location = hoverLink;
}
}
}
</script>
</head>
<body onload="OnLoad();">
<canvas id="myCanvas" width="450" height="250" style="border:1px solid #eee;">
Canvas is not supported in your browser ! :(
</canvas>
<canvas id="myCanvas1" width="50" height="50" style="background-color:white;border:1px solid blue;position:absolute;left:-200px;top:100px;">
</canvas>
</body>
</html>

How to move an image depending on mouse location using JS?

I would like an image to move to the left if the mouse is to the left of the screen and to the right if the mouse to the right of the screen, using javascript, here is the code I have so far:
var dirx = 0;
var spdx = 35;
var imgLeftInt;
var imgTopInt;
var imgHeight;
var imgWidth;
var divWidth;
var divHeight;
var t;
var tempX;
var tempY;
So I'm pretty sure I'm not missing any variables...
function animBall(on) {
imgLeftInt = parseInt(document.images['logo'].style.left);
imgTopInt = parseInt(document.images['logo'].style.top);
imgHeight = parseInt(document.images['logo'].height);
imgWidth = parseInt(document.images['logo'].width);
divWidth = parseInt(document.images['container'].width);
if (tempX > 779){
dirx = 1;
}
else if(tempX < 767){
dirx = 2;
}
else {
spdx = 0;
}
So if tempX, which should be the x coordinate of the mouse location, is bigger than 779, which is the halfway point of the div tag, the image should go right. If it's less than that, it should go left, and otherwise, the speed should be zero, as in it should stay still.
if(dirx == 1){
goRight();
} else if(dirx == 2) {
goLeft();
}
}
function getMouseXY(e) {
tempX = e.clientX;
tempY = e.clientY;
}
I found hundreds of different ways to get the mouse location, but this was off W3C so I assume it works.
function goRight() {
document.images['logo'].style.left = imgLeftInt+spdx +"px";
if (imgLeftInt > (divWidth-imgWidth)){
dirx = 2;
spdx= 20;
}
}
function goLeft() {
document.images['logo'].style.left = (imgLeftInt-spdx) +"px";
if (imgLeftInt < 5){
dirx = 1;
spdx= 20;
}
}
</script>
So that's my whole script.
<div id="container" onmousemove="getMouseXY(event);" width="1546" height="423">
Start Animation Stop Animation <br />
<img src="http://qabila.tv/images/logo_old.png" style="position:absolute;left:10px;top:20px;" id="logo" />
</div>
I left the dependency on the mouse location to the very end so the animation script works fine (or at least worked, unless I broke something trying to get it to read the mouse location).
Any ideas what I'm doing wrong??
If it's any help, I've hosted the code here.
I went to your link and tried debugging your code. I get an error on line 21 because your document has no "container" image ("container" is a div).
At the start of your question, you said you wanted to know mouse position relative to center of "screen". For that, you'd probably want to use window.innerWidth instead of the width attribute that you set on your div.
Well that needed a whole load of work, anyway, I have done some of it for you and you can now see things partially working, but you will need to play with it on jsfiddle. Perhaps you can now open some specific questions regarding getting this to work.
<div id="container" width="1546" height="423"> <a id="start" href="#">Start Animation</a> <a id="stop" href="#">Stop Animation</a>
<br />
<img src="http://qabila.tv/images/logo_old.png" style="position:absolute;left:10px;top:20px;" id="logo" />
</div>
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */
(function () {
"use strict";
var start = document.getElementById("start"),
stop = document.getElementById("stop"),
container = document.getElementById("container"),
logo = document.getElementById("logo"),
dirx = 0,
spdx = 35,
imgLeftInt,
imgTopInt,
imgHeight,
imgWidth,
divWidth,
divHeight,
t,
tempX,
tempY;
function getMouseXY(e) {
tempX = e.clientX;
tempY = e.clientY;
}
function goRight() {
logo.style.left = imgLeftInt + spdx + "px";
if (imgLeftInt > (divWidth - imgWidth)) {
dirx = 2;
spdx = 20;
}
}
function goLeft() {
logo.style.left = (imgLeftInt - spdx) + "px";
if (imgLeftInt < 5) {
dirx = 1;
spdx = 20;
}
}
// attribute on unused
function animBall(on) {
imgLeftInt = parseInt(logo.style.left, 10);
imgTopInt = parseInt(logo.style.top, 10);
imgHeight = parseInt(logo.height, 10);
imgWidth = parseInt(logo.width, 10);
divWidth = parseInt(container.width, 10);
if (tempX > 779) {
dirx = 1;
} else if (tempX < 767) {
dirx = 2;
} else {
spdx = 0;
}
if (dirx === 1) {
goRight();
} else if (dirx === 2) {
goLeft();
}
}
function startAnim() {
t = setInterval(animBall, 80);
}
start.addEventListener("click", startAnim, false);
function stopAnim() {
clearInterval(t);
}
stop.addEventListener("click", stopAnim, false);
container.addEventListener("mousemove", getMouseXY, false);
}());
Why don't you usee the html5 canvas and gee.js
Here's the js fiddle result (it may take a while to load, but that's fault of jsfiddle, the script will load much faster once on your website): http://jsfiddle.net/wLCeE/7/embedded/result/
and here's the much simpler code to make it work:
var g = new GEE({
width: 500,
height: 423,
container: document.getElementById('canvas')
});
var img = new Image(); // Create new img element
img.onload = function () {
demo(g)
};
img.src = 'http://qabila.tv/images/logo_old.png'; // Set source path
function demo(g) {
var style = "left"
g.draw = function () {
if (g.mouseX > g.width / 2 && style == "left") styleRight()
else if (g.mouseX < g.width / 2 && style == "right") styleLeft()
}
function styleLeft() {
style = "left"
g.ctx.clearRect(0, 0, g.width, g.height)
g.ctx.drawImage(img, 0, 0)
}
function styleRight() {
style = "right"
g.ctx.clearRect(0, 0, g.width, g.height)
g.ctx.drawImage(img, g.width - img.width, 0)
}
}

Categories