Javascript - "print" mouse on document by cords - javascript

I have list of mouse cords (x,y)
Because it is impossible to move mouse with javascript, I would like to print a fake mouse on the document followed by the cords that I already have.
Is it possible? How?

My solution was to print PNG that shows the mouse and hide the original one with css:
createCursor: function() {
var cursor = document.createElement("img");
cursor.src = chrome.extension.getURL('pics/cursor.png');
cursor.style.zIndex = "9999";
cursor.setAttribute("id", "recordMeCursor");
var body = document.getElementsByTagName("BODY")[0];
body.style.cursor = 'none';
body.appendChild(cursor);
},
moveCursor: function(cords, i, callback) {
var cursor = document.getElementById("recordMeCursor");
setTimeout(function() {
cursor.style.position = "absolute";
cursor.style.left = cords.x+'px';
cursor.style.top =cords.y+'px';
return callback('OK');
}, i * 50);
},
destroyMouse: function() {
var cursor = document.getElementById("recordMeCursor");
cursor.parentNode.removeChild(cursor);
var body = document.getElementsByTagName("BODY")[0];
body.style.cursor = 'default';
}

Related

move mouse but only on the width of the div

I just adapted this code to play a sequence of images when you move the mouse on the x axis. I have two questions about this code:
I can't adapt the length to the width of the div, not to the width of the whole window.
There are "flashes" when I move the mouse, I have the impression that it comes from the loading of the images?
Thanks for your help.
Live: https://codepen.io/nicolastilly/pen/jOBKxKK
Code:
var blocWidth;
var imgblock = ['https://assets.codepen.io/265602/frame0.png',
'https://assets.codepen.io/265602/frame1.png',
'https://assets.codepen.io/265602/frame2.png',
'https://assets.codepen.io/265602/frame3.png',
'https://assets.codepen.io/265602/frame4.png',
'https://assets.codepen.io/265602/frame5.png',
'https://assets.codepen.io/265602/frame6.png',
'https://assets.codepen.io/265602/frame7.png',
'https://assets.codepen.io/265602/frame8.png',
'https://assets.codepen.io/265602/frame9.png',
'https://assets.codepen.io/265602/frame10.png',
'https://assets.codepen.io/265602/frame11.png',
'https://assets.codepen.io/265602/frame12.png',
'https://assets.codepen.io/265602/frame13.png',
'https://assets.codepen.io/265602/frame14.png',
'https://assets.codepen.io/265602/frame15.png',
'https://assets.codepen.io/265602/frame16.png',
'https://assets.codepen.io/265602/frame17.png',
'https://assets.codepen.io/265602/frame18.png',
'https://assets.codepen.io/265602/frame19.png',
'https://assets.codepen.io/265602/frame20.png'];
function onMouseMove(e) {
var x = e.pageX;
var theimg = imgblock[parseInt(x / blocWidth * imgblock.length)];
$('.bloc1').css("background-image", "url('" + theimg + "')");
}
function onResize() {
blocWidth = $('.bloc1').width();
}
function onResize() {
blocWidth = $(document).width();
}
$(window).on('mousemove', onMouseMove);
$(window).resize(onResize);
onResize();
As for flickering, you can circumvent that by preloading the images
let loaded = 0 ;
imgblock.forEach(url => {
let img=new Image();
img.src=url;
img.onload = onImgLoaded
})
function onImgLoaded() {
loaded++;
if (loaded == imgblock.length-1) console.log('all images have pre-loaded');
}
As for the sizing issue, you need to take into account if you're mousing over the target and accounting for the div's left value in your calculations. Get rid of both these:
function onResize() {
blocWidth = $('.bloc1').width();
}
function onResize() {
blocWidth = $(document).width();
}
replace with:
let blocStartX;
function onResize() {
let pos = $(".bloc1")[0].getBoundingClientRect()
console.log(pos)
blocWidth = pos.width;
blocStartX = pos.x
}
Detect the mouseover:
let isOnDiv = false
$(".bloc1").mouseenter(function(){isOnDiv=true;});
$(".bloc1").mouseleave(function(){isOnDiv=false;});
and add this to the top of your mousemove function:
if (!isOnDiv) return
var x = e.pageX - blocStartX;
https://codepen.io/john-tyner/pen/wvJXXQZ

Adding image on mouse click is not adding image on correct co-ordinates

I am using pdf.js to view the pdf, and adding canvas over the top of the each page to add image on click. Images are adding on mouse click but its not on exact position..
$('.page').on('click', function(e) {
console.log("fgdfgdfg")
console.log(e)
if($("#hotspotTool").hasClass('active')){
var pageIndex = window.PDFViewerApplication.pdfViewer.currentPageNumber;
var page = window.PDFViewerApplication.pdfViewer.getPageView(pageIndex);
if ($(e.target).parent().hasClass('page')) {
var pid = $(e.target).parent().attr("id");
console.log(pid)
var canvas=document.getElementById(pid).getElementsByClassName("annotationLayer_svg")[0]
console.log(canvas)
var canv_id = $(canvas).attr('id')
if(canvas){
count++
var ctx = canvas.getContext("2d");
base_image = new Image();
base_image.src = '/images/dot.png';
base_image.id="hotspot"+count
base_image.draggable="true"
console.log(base_image)
var x = e.offsetX - base_image.width/2,
y = e.offsetY - base_image.height/2;
console.log(x,y)
ctx.drawImage(base_image,x,y);
ctx.save();
$("#hotspotTool").removeClass("active");
$('#hotspotmodel').modal('show');
$('#submit').on('click', function() {
$(this).data('clicked', true);
$("#hotspotform").valid();
if( $("#hotspotform").valid()){
$('#hotspotmodel').modal('hide');
var page_value = document.getElementById("pagelink").value
var spot_link = window.location.href+"page="+page_value
var anchor = document.createElement("A");
anchor.appendChild(base_image)
anchor.setAttribute("href", spot_link);
}
});
}
}
}
})
How can I able to add image on mouse click on exact position

jQuery change div position onMouseOver

I have the svg map with pins on it. I want to make the application that shows the description of the pin, when user put the mouse on it. The thing is, that the description should be in the mouse position. I've already done things like changing color onMouseOver and manipulate with all different css parameters. But I have problem with changing the div position.
In the same part of code when I put:
document.getElementById("test").style.color = "red";
the color is changing.
but when I do this:
document.getElementById("test").style.left = 500;
nothing happens.
I was trying with all those solution:
$("test").css({top: 200, left: 200});
and lots of others, but I have no idea why it doesnt work.
my jQuery code:
jQuery(document).ready(function() {
jQuery('img.svg').each(function(){
var mouseX;
var mouseY;
var $img = jQuery(this);
var imgURL = $img.attr('src');
jQuery.get(imgURL, function (data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Replace image with new SVG
$img.replaceWith($svg);
// Add an handler
jQuery('#pins path').each(function () {
jQuery(this).click(function () {
var post_slug = jQuery(this).attr('id');
var url = "http://127.0.0.1:8000/posts/post_slug".replace("post_slug", post_slug); //TODO
window.location = url;
});
jQuery(this).mouseover(function (e) {
mouseX = e.pageX;
mouseY = e.pageY;
var post_slug = jQuery(this).attr('id');
// using string concat due to name conficts with "path id" in svg map
//document.getElementById("popup_".concat(post_slug)).style.display = 'block';
document.getElementById("popup_".concat(post_slug)).style.top = mouseY;
document.getElementById("popup_".concat(post_slug)).style.left = mouseX;
document.getElementById("popup_".concat(post_slug)).style.color = "red";
});
jQuery(this).mouseout(function () {
var post_slug = jQuery(this).attr('id');
// using string concat due to name conficts with "path id" in svg map
document.getElementById("popup_".concat(post_slug)).style.display = 'none';
});
});
});
});
});
The divs are dynamically created according to objects in my django template.
for (var i = 0; i < pin_slugs.length; i++) {
var popup = document.createElement("div");
popup.id = "popup_".concat(pin_slugs[i]);
popup.title = pin_slugs[i];
popup.innerHTML = pin_slugs[i];
document.body.appendChild(popup);
}
I'm struggling with it for a long time. Can anyone help?
left, right, top, bottom properties will not work with default position value which is static. You should give position:absolute/relative. Best one to give in this scenario is absolute.
I solved it out. The solution was simple.
mouseX + "px";
and in my css I needed to put:
position: absolute;

Creating a click event in Javascript Canvas

I'm having trouble creating a click event for my Javascript canvas game. So far I have been following a tutorial, however the way you interact with the game is through mouse hover. I would like to change it so that instead of hovering over objects in the canvas to interact, I instead use a mouse click.
The following is the code I use to detect the mouse hover.
getDistanceBetweenEntity = function (entity1,entity2) //return distance
{
var vx = entity1.x - entity2.x;
var vy = entity1.y - entity2.y;
return Math.sqrt(vx*vx+vy*vy);
}
testCollisionEntity = function (entity1,entity2) //return if colliding
{
var distance = getDistanceBetweenEntity(entity1,entity2);
return distance < 50;
}
I then use this in a loop to interact with it.
var isColliding = testCollisionEntity(player,nounList[key]);
if(isColliding)
{
delete nounList[key];
player.score = player.score + 10;
}
Below is a complete copy of my game at its current state.
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
//Setting the height of my canvas
var HEIGHT = 500;
var WIDTH = 500;
//Player class
var player =
{
x:50,
spdX:30,
y:40,
spdY:5,
name:'P',
score:0,
};
//Creating arrays
var nounList ={};
var adjectivesList ={};
var verbsList ={};
getDistanceBetweenEntity = function (entity1,entity2) //return distance
{
var vx = entity1.x - entity2.x;
var vy = entity1.y - entity2.y;
return Math.sqrt(vx*vx+vy*vy);
}
testCollisionEntity = function (entity1,entity2) //return if colliding
{
var distance = getDistanceBetweenEntity(entity1,entity2);
return distance < 50;
}
Nouns = function (id,x,y,name)
{
var noun =
{
x:x,
y:y,
name:name,
id:id,
};
nounList[id] = noun;
}
Adjectives = function (id,x,y,name)
{
var adjective =
{
x:x,
y:y,
name:name,
id:id,
};
adjectivesList[id] = adjective;
}
Verbs = function (id,x,y,name)
{
var verb =
{
x:x,
y:y,
name:name,
id:id,
};
verbsList[id] = verb;
}
document.onmousemove = function(mouse)
{
var mouseX = mouse.clientX;
var mouseY = mouse.clientY;
player.x = mouseX;
player.y = mouseY;
}
updateEntity = function (something)
{
updateEntityPosition(something);
drawEntity(something);
}
updateEntityPosition = function(something)
{
}
drawEntity = function(something)
{
ctx.fillText(something.name,something.x,something.y);
}
update = function ()
{
ctx.clearRect(0,0,WIDTH,HEIGHT);
drawEntity(player);
ctx.fillText("Score: " + player.score,0,30);
for(var key in nounList)
{
updateEntity(nounList[key]);
var isColliding = testCollisionEntity(player,nounList[key]);
if(isColliding)
{
delete nounList[key];
player.score = player.score + 10;
}
}
for(var key in adjectivesList)
{
updateEntity(adjectivesList[key])
var isColliding = testCollisionEntity(player,adjectivesList[key]);
if(isColliding)
{
delete adjectivesList[key];
player.score = player.score - 1;
}
}
for(var key in verbsList)
{
updateEntity(verbsList[key])
var isColliding = testCollisionEntity(player,verbsList[key]);
if(isColliding)
{
delete verbsList[key];
player.score = player.score - 1;
}
}
if(player.score >= 46)
{
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.fillText("Congratulations! You win!",50,250);
ctx.fillText("Refresh the page to play again.",50,300);
}
}
Nouns('N1',150,350,'Tea');
Nouns('N2',400,450,'Park');
Nouns('N3',250,150,'Knee');
Nouns('N4',50,450,'Wall');
Nouns('N5',410,50,'Hand');
Adjectives('A1',50,100,'Broken');
Adjectives('A2',410,300,'Noisy');
Verbs('V1',50,250,'Smell');
Verbs('V2',410,200,'Walk');
setInterval(update,40);
To summarize all I want to do is change it so that instead of mousing over words to delete them you have to click.
(Apologies for not using correct terminology in places, my programming knowledge is quite limited.)
You can have your canvas listen for mouse clicks on itself like this:
// get a reference to the canvas element
var canvas=document.getElementById('ctx');
// tell canvas to listen for clicks and call "handleMouseClick"
canvas.onclick=handleMouseClick;
In the click handler, you'll need to know the position of your canvas relative to the viewport. That's because the browser always reports mouse coordinates relative to the viewport. You can get the canvas position relative to the viewport like this:
// get the bounding box of the canvas
var BB=canvas.getBoundingClientRect();
// get the left X position of the canvas relative to the viewport
var BBoffsetX=BB.left;
// get the top Y position of the canvas relative to the viewport
var BBoffsetY=BB.top;
So your mouseClickHandler might look like this:
// this function will be called when the user clicks
// the mouse in the canvas
function handleMouseClick(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// get the canvas postion relative to the viewport
var BB=canvas.getBoundingClientRect();
var BBoffsetX=BB.left;
var BBoffsetY=BB.top;
// calculate the mouse position
var mouseX=e.clientX-BBoffsetX;
var mouseY=e.clientY-BBoffsetY;
// report the mouse position using the h4
$position.innerHTML='Click at '+parseInt(mouseX)+' / '+parseInt(mouseY);
}
If your game doesn't let the window scroll or resize then the canvas postion won't change relative to the viewport. Then, for better performance, you can move the 3 lines relating to getting the canvas position relative to the viewport to the top of your app.
// If the browser window won't be scrolled or resized then
// get the canvas postion relative to the viewport
// once at the top of your app
var BB=canvas.getBoundingClientRect();
var BBoffsetX=BB.left;
var BBoffsetY=BB.top;
function handleMouseClick(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// calculate the mouse position
var mouseX=e.clientX-BBoffsetX;
var mouseY=e.clientY-BBoffsetY;
// report the mouse position using the h4
$position.innerHTML='Click at '+parseInt(mouseX)+' / '+parseInt(mouseY);
}

Javascript: visual issue when dragging image by eventListener

I'm making a script to drag an image in a frame using eventListener instead of .onSomeEvent:
var destForm, destFoto, destX, destY;
function destaqueIni(){
destForm = document.forms["form_destaque"];
destFoto = new Object();
destFoto.img = document.getElementById("form_destaque_foto");
destFoto.w = destFoto.img.clientWidth;
destFoto.h = destFoto.img.clientHeight;
destFoto.x = 0; //Number(destForm.fotoDestaque_x.value);
destFoto.y = 0; //Number(destForm.fotoDestaque_y.value);
destFoto.escala = Number(destForm.fotoDestaque_escala.value);
//
document.getElementById("form_destaque_janela").style.height = "380px";
//
destFoto.img.draggable = true;
destFoto.img.addEventListener("dragstart", destaqueFotoDragStart, false);
destFoto.img.addEventListener("dragend", destaqueFotoDrag, false);
}
function destaqueFotoDragStart(evt){
//evt.preventDefault();
//console.log("destaqueFotoDrag: Foto Arrastada... img.x: "+evt.clientX+" destX: "+destX);
destX = evt.clientX;
destY = evt.clientY;
}
function destaqueFotoDrag(evt){
evt.preventDefault();
//console.log("destaqueFotoDrag: Foto Solta... img.x: "+evt.clientX+" destX: "+destX);
var x = destFoto.x + (evt.clientX-destX);
var y = destFoto.y + (evt.clientY-destY);
destForm.fotoDestaque_x.value = x;
destForm.fotoDestaque_y.value = y;
destaqueFotoAtualizar();
}
function destaqueFotoAtualizar(){
destFoto.img.style.left = String(Math.ceil(destForm.fotoDestaque_x.value/2))+"px";
destFoto.img.style.top = String(Math.ceil(destForm.fotoDestaque_y.value/2))+"px";
}
It works (still working, but is dragging). So the image will be moved but before the image be placed at the new x,y coordinates, the browser do an animation back to the original place - after it jumps to the right place. This is a pretty bug! How do I prevent the browser from making the animation after release? I tried preventDefault() but didn't work...
Search "stop drag image in browsers" and you will get your answer.
$("img").mousedown(function(){ return false; });
$(document).on("dragstart", function() { return false; });
$(document).on("dragstart", function(e) {
if (e.target.nodeName.toUpperCase() == "IMG") { return false; }
});
<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>
<div onmousedown="return false">asd</div>
//also css has selection rules for different browser

Categories