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';
}
Using the Yahoo Weather API.
When trying to set the style margins via JS, nothing happens.
Here is my script:
<script>
var cBackFunction = function (data) {
console.log(data);
var location = data.query.results.channel.location;
var condition = data.query.results.channel.item.condition;
var wind = data.query.results.channel.wind;
var units = data.query.results.channel.units;
var link = data.query.results.channel.link;
var lastUpdated = data.query.results.channel.lastBuildDate;
var conditionCode = condition.code;
var conditionText = condition.text;
var img = document.createElement("IMG");
img.src = "https://s.yimg.com/zz/combo?a/i/us/we/52/" + conditionCode + ".gif";
img.style.marginLeft = "140px";
document.getElementById('Weather-Description2').appendChild(img);
document.getElementById('Weather-Location2').innerHTML = location.city;
document.getElementById('Weather-Region2').innerHTML = location.region;
document.getElementById('Weather-Temp2').innerHTML = condition.temp;
document.getElementById('Weather-Unit2').innerHTML = units.temperature;
document.getElementById('Weather-WindSpeed2').innerHTML = wind.speed;
document.getElementById('Weather-Link2').href = link;
document.getElementById('lastUpdate2').innerHTML = lastUpdated;
document.getElementById('Weather-text2').innerHTML = "["+conditionText+"]";
document.getElementById('Weather-text2').style.marginLeft = 'auto'; //not working
document.getElementById('Weather-text2').style.marginRight = 'auto'; // not working
}
HTML:
<strong id="Weather-text2"></strong>
If I change the auto to a specific pixel like "100px" then it works.. can auto be used in JS for margins? The reason for auto on both marginLeft and marginRight is to auto-center the element. If so, how do I implement that correctly?
A <strong> element is, by default, display: inline.
Auto margins centre elements which are display: block (although since you would have width: auto as the default, this would have no practical effect unless you also reduced the width).
Set text-align: center on the nearest block ancestor element to centre the text.
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);
}
I've used some source for a transparent overlay in JavaScript:
function grayOut(vis, options)
{
var options = options || {};
var zindex = 50;
var opacity = 70;
var opaque = (opacity / 100);
var bgcolor = options.bgcolor || '#000000';
var dark=document.getElementById('darkenScreenObject');
if (!dark) {
// The dark layer doesn't exist, it's never been created. So we'll
// create it here and apply some basic styles.
// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
var tbody = document.getElementsByTagName("body")[0];
var tnode = document.createElement('div'); // Create the layer.
tnode.style.position='absolute'; // Position absolutely
tnode.style.top='0px'; // In the top
tnode.style.left='0px'; // Left corner of the page
tnode.style.display='none'; // Start out Hidden
tnode.id='darkenScreenObject'; // Name it so we can find it later
tbody.appendChild(tnode);
/*
var pTag = document.createElement("P");
var txtProcessing = document.createTextNode("Processing GIF...");
tnode.appendChild(txtProcessing);
*/
}
if (vis)
{
// Calculate the page width and height
if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) )
{
var pageWidth = document.body.scrollWidth+'px';
var pageHeight = document.body.scrollHeight+'px';
}
else if( document.body.offsetWidth )
{
var pageWidth = document.body.offsetWidth+'px';
var pageHeight = document.body.offsetHeight+'px';
}
else
{
var pageWidth='100%';
var pageHeight='100%';
}
//set the shader to cover the entire page and make it visible.
dark.style.opacity=opaque;
dark.style.MozOpacity=opaque;
dark.style.filter='alpha(opacity='+opacity+')';
dark.style.zIndex=zindex;
dark.style.backgroundColor=bgcolor;
dark.style.width= pageWidth;
dark.style.height= pageHeight;
dark.style.display='block';
var txt = document.createTextNode("This text was added.");
dark.appendChild(txt);
}
else
{
dark.style.display='none';
}
}
My problem is I'm trying to get some text to show up on the transparent layer but I can't get it to work. Any thoughts?
Your text node is created on overlay but is invisible cause of text color.
check Fiddle where text color is set to red.
dark.style.color = 'red';
I just started working with the easeljs library. I have created a canvas with a stage and it works.
I want to add bitmaps as buttons and add them side by side in the bottom on the stage.
I have tried with the following, but it place the bitmaps on top on each other.
var button = new createjs.Bitmap(queue.getResult("largebrick"));
var contentWidth = document.getElementById("content").offsetWidth;
var contentHeight = document.getElementById("content").offsetHeight;
var container = new createjs.Container();
stage.addChild(container);
stage.enableMouseOver(10);
for(var i = 0; i <10; i++){
button.x = 0 + button.getBounds().width * i;
button.y = contentHeight - button.getBounds().height;
button.addEventListener("mouseover", function() { document.body.style.cursor = 'pointer'; });
button.addEventListener("mouseout", function() { document.body.style.cursor = 'default'; });
button.addEventListener("click", function(event) {addBricks(button); });
container.addChild(button);
}
I hope some of you guys can help.
A couple things here. You need to create a new instance of the button inside the loop, otherwise you are just moving the original instance of button on each iteration. In this example, I simplified everything a bit by using a shape, but you could easily do the same with your Bitmap.
var xPos = 0;
for(var i = 0; i < 10; i++){
var button = new createjs.Bitmap(queue.getResult("largebrick"));
button.cursor = "pointer";
button.x = xPos;
button.y = contentHeight - 50;
xPos += 60;
container.addChild(button);
}
Also, createjs supports defining cursors as a property of a display object like so
button.cursor = "pointer";
which should simplify your code a little.