HTML
<div id="container">
<div id="wrapper">
</div>
<span id = "waveNum">Current Wave: 0</span>
<input type = "button" value = "Start Game" onclick = "startGame()"></input>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="main.js"></script>
</body>
Javascript
var keyArray = [];
var currentWave = 1;
var player;
var player2;
function initiate(){
player = new createPlayer(150,50,"player1","relative","blue");
player2 = new createPlayer(150,0,"player2","relative","green");
}
function startGame() {
point();
}
function createPlayer(l,t,id,pos,color){
this.speed = 3;
this.width = 25;
this.height = 25;
this.left = l;
this.top = t;
this.id = id;
this.model = $("<div id=" + id + "/>")
.css({"backgroundColor":color,"height":this.height,"width":this.width,
"left":this.left,"top":this.top,"position":pos})
$('#wrapper').append($(this.model));
}
function point(){
leftP = parseInt(Math.random()*970);
topP = parseInt(Math.random()*580);
$points = $("<div class=point/>")
.css({"backgroundColor":"yellow","height":"10px","width":"10px","left":0,
"top":0,"position":"relative"})
$('#wrapper').append($points)
}
function update(){
//left
if(keyArray[65]){
var newLeft = parseInt(player.left)-player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//right
if(keyArray[68]){
var newLeft = parseInt(player.left)+player.speed+"px"
player.left = newLeft;
document.getElementById(player.id).style.left = newLeft;
}
//up
if(keyArray[87]){
var newTop = parseInt(player.top)-player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//down
if(keyArray[83]){
var newTop = parseInt(player.top)+player.speed+"px"
player.top = newTop;
document.getElementById(player.id).style.top = newTop;
}
//player2
//left
if(keyArray[37]){
var newLeft = parseInt(player2.left)-player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//right
if(keyArray[39]){
var newLeft = parseInt(player2.left)+player2.speed+"px"
player2.left = newLeft;
document.getElementById(player2.id).style.left = newLeft;
}
//up
if(keyArray[38]){
var newTop = parseInt(player2.top)-player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
//down
if(keyArray[40]){
var newTop = parseInt(player2.top)+player2.speed+"px"
player2.top = newTop;
document.getElementById(player2.id).style.top = newTop;
}
blockade();
requestAnimationFrame(update);
}
function blockade(){
var elemLeft = parseInt($('#wrapper').css('left'));
var elemWidth = parseInt($('#wrapper').css('width'));
var elemTop= parseInt($('#wrapper').css('height'));
//blocks players from moving outside of game
if(parseInt(player.left) + player.width >= elemLeft+elemWidth){
player.left = elemWidth - player.width - 2;
}
if(parseInt(player.top) + player.height >= elemTop){
player.top = elemTop - player.height - 2;
}
if(parseInt(player.top) < 3){
player.top = 3;
}
if(parseInt(player.left) < 3){
player.left = 3;
}
if(parseInt(player2.left) + player2.width >= elemLeft+elemWidth){
player2.left = elemWidth - player2.width - 2;
}
if(parseInt(player2.top) + player2.height >= elemTop){
player2.top = elemTop - player2.height - 2;
}
if(parseInt(player2.top) < 3){
player2.top = 3;
}
if(parseInt(player2.left) < 3){
player2.left = 3;
}
}
window.onkeydown = function(page){
keyArray[page.keyCode] = page.type === 'keydown';
}
window.onkeyup = function(page){
keyArray[page.keyCode] = page.type === 'keydown'
}
CSS
html, body {margin: 0; height: 100%; overflow: hidden}
#container{
width:80%;
height:60%;
display: block;
text-align:center;
margin: 0 auto;
}
#wrapper{
left:0px;
width:1000px; /* 100% */
height:600px;
border:1px solid lime;
margin:0 auto;
background-color:black;
}
#player1, .point {
float: left;
clear: both;
}
body{
background-color:black;
}
#waveNum{
color:white;
font-size:200%;
}
.point {
overflow: auto;
}
So currently I need my point() function to generate a random div within the <div id="wrapper"> which it is but after a few different spawns, does not stay within the wrapper div eventually. It seems like the container of the point() seems to be shifting down. The more that is generated the more often it appears to the bottom and outside of the container.
Eventually my idea is for all of them to have the same top and left original positions in that way I could use my player and player2 to touch them (match left and top positions) and make them disappear like they are being collected like points. I also cant get them to have the same origin point. I think these issues might be related
You can use to make appeared specific div
z-index: 0
Try adding absolute positioning to your wrapper div and relative positioning to the container div:
#container {
position: relative;
}
#wrapper {
position: absolute;
top: 0;
left: 0;
}
This takes the div out of normal flow from the rest of the document.
See here for more explanations on why this works.
Related
how do I stop the following interval and make the alien move backwards when it reaches 700px? I know I can do this with CSS but I want to do this strictly with JS. I don't understand how to stop the interval once it reaches the 700px left...
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = left + 2 + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
clearInterval(interval);
alien.style.left = left - 10 + "px";
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>
Any help?
Introduce a speed variable which will switch from 2 to -2 when it reaches the right limit. You should then do the same at the left side, and switch the speed from -2 to 2 again.
As you want to keep moving, the stop function is no longer needed.
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
let speed = 2;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) speed = -2;
else if (left <= 0) speed = 2;
alien.style.left = left + speed + "px";
}
interval = setInterval(flow, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>
To move your element you use left + 2 so it always is moving to one direction.
So when reaching 700px mark you should reverse it to be left - 2 until it's 0.
I have modified your code adding currentDirection variable
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
var currentDirection = 1;
var hasMoved = false;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = (left + 2 * currentDirection) + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
currentDirection = -1;
} else if (left < 0) {
currentDirection = 1;
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
background: gold;
height: 20px;
width: 20px;
}
.alien {
background: red;
height: 20px;
width: 20px;
position: absolute;
}
<div class="game">
</div>
Trying to add this image hover effect to the featured image in a blog post template in Wordpress. Currently the JS is calling an image URL, but I want the effect to target the featured image of the post template. I think it may be possible using PHP in the JS file but im not sure how to do it, can anyone help me out please?
// options
var options = {
imgSrc : "https://unsplash.it/g/1024/768?image=887",
containerName : "tileContainer",
grid : false,
tileWidth : 80,
tileHeight : 80,
mouseTrail:true
}
// ----------------------------------------------------------
var tileWidth, tileHeight, numTiles, tileHolder, tileContainer;
var directionX, directionY;
var imgOriginalWidth, imgOriginalHeight;
var imgCoverWidth, imgCoverHeight;
var imageLoaded = false;
numTiles=0;
tileWidth = options.tileWidth;
tileHeight = options.tileHeight;
tileContainer = document.getElementsByClassName(options.containerName)[0];
function init(){
if(options.grid == false)tileContainer.className += " noGrid";
//preload image and get original image size, then create tiles
var image = new Image();
image.src = options.imgSrc;
image.onload = function(e){
imageLoaded = true;
imgOriginalWidth = e.currentTarget.width;
imgOriginalHeight = e.currentTarget.height;
createTileHolder();
checkTileNumber();
positionImage();
addListeners();
};
}
function resizeHandler()
{
if(imageLoaded == false)return;
//not working yet
checkTileNumber();
positionImage();
}
function createTileHolder(){
tileHolder = document.createElement('div');
tileHolder.className = "tileHolder";
tileHolder.style.position = "absolute";
tileHolder.style.top = "50%";
tileHolder.style.left = "50%";
tileHolder.style.transform = "translate(-50%, -50%)";
tileContainer.appendChild(tileHolder);
}
function checkTileNumber()
{
tileHolder.style.width = Math.ceil(tileContainer.offsetWidth / tileWidth) * tileWidth + "px";
tileHolder.style.height = Math.ceil(tileContainer.offsetHeight / tileHeight) * tileHeight + "px";
var tilesFitInWindow = Math.ceil(tileContainer.offsetWidth / tileWidth) * Math.ceil(tileContainer.offsetHeight / tileHeight);
if(numTiles < tilesFitInWindow){
for (var i=0, l=tilesFitInWindow-numTiles; i < l; i++){
addTiles();
}
}else if(numTiles > tilesFitInWindow){
for (var i=0, l=numTiles-tilesFitInWindow; i < l; i++){
removeTiles();
}
}
}
function addTiles()
{
var tile = document.createElement('div');
tile.className = "tile";
//maintain aspect ratio
imgCoverWidth = tileContainer.offsetWidth;
imgCoverHeight = tileContainer.offsetHeight;
if(imgOriginalWidth > imgOriginalHeight){
imgCoverHeight = imgOriginalHeight / imgOriginalWidth * imgCoverWidth;
}else{
imgCoverWidth = imgOriginalWidth / imgOriginalHeight * imgCoverHeight;
}
tile.style.background = 'url("'+options.imgSrc+'") no-repeat';
tile.style.backgroundSize = imgCoverWidth + "px " + imgCoverHeight + "px";
tile.style.width = tileWidth + "px";
tile.style.height = tileHeight + "px";
document.querySelectorAll(".tileHolder")[0].appendChild(tile);
tile.addEventListener("mouseover", moveImage);
numTiles++;
}
function removeTiles()
{
var tileToRemove = document.querySelectorAll(".tile")[0];
tileToRemove.removeEventListener("mouseover", moveImage);
TweenMax.killTweensOf(tileToRemove);
tileToRemove.parentNode.removeChild(tileToRemove);
numTiles--;
}
function addListeners(){
if(options.mouseTrail){
document.addEventListener('mousemove', function (event) {
directionX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
directionY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
});
}
}
function positionImage(){
for(var t=0, l=numTiles; t < l; t++)
{
var nowTile = document.querySelectorAll(".tile")[t];
var left = (-nowTile.offsetLeft - (tileHolder.offsetLeft - (tileHolder.offsetWidth/2)));
var top = (-nowTile.offsetTop - (tileHolder.offsetTop - (tileHolder.offsetHeight/2)));
nowTile.style.backgroundPosition = left + "px " + top + "px";
}
}
function resetImage(nowTile){
var left = (-nowTile.offsetLeft - (tileHolder.offsetLeft - (tileHolder.offsetWidth/2)));
var top = (-nowTile.offsetTop - (tileHolder.offsetTop - (tileHolder.offsetHeight/2)));
TweenMax.to(nowTile, 1, {backgroundPosition:left + "px " + top + "px", ease:Power1.easeInOut});
}
function moveImage(e){
var nowTile = e.currentTarget
var minWidth = -tileContainer.offsetWidth+nowTile.offsetWidth;
var minHeight = -tileContainer.offsetHeight+nowTile.offsetHeight;
var nowLeftPos = (-nowTile.offsetLeft - (tileHolder.offsetLeft - (tileHolder.offsetWidth/2)));
var nowTopPos = (-nowTile.offsetTop - (tileHolder.offsetTop - (tileHolder.offsetHeight/2)))
var offset = 60;
var left = nowLeftPos;
var top = nowTopPos;
if(options.mouseTrail){
//direction-aware movement
if(directionX > 0){
left = nowLeftPos + offset;
}else if(directionX < 0){
left = nowLeftPos - offset;
}
if(directionY > 0){
top = nowTopPos + offset;
}else if(directionY < 0){
top = nowTopPos - offset;
}
}else{
//random movement
left = getRandomInt(nowLeftPos - offset , nowLeftPos + offset);
top = getRandomInt(nowTopPos - offset, nowTopPos + offset);
}
// bounds
if(left < minWidth)left=minWidth;
if(left > 0)left=0;
if(top < minHeight)top=minHeight;
if(top > 0)top=0;
//tween
TweenMax.to(nowTile, 1.5, {backgroundPosition:left + "px " + top + "px", ease:Power1.easeOut, onComplete:resetImage, onCompleteParams:[nowTile]});
}
///////////////////////////////////////////////////////////////////
init();
// handle event
//window.addEventListener("optimizedResize", resizeHandler);
////////////////////////UTILS//////////////////////////////////////
//////////////////////////////////////////////////////////////////
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
(function() {
var throttle = function(type, name, obj) {
obj = obj || window;
var running = false;
var func = function() {
if (running) { return; }
running = true;
requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
};
/* init - you can init any event */
throttle("resize", "optimizedResize");
})();
body{background-color:#1A1919;text-align:center;}
.tileContainer{
border:10px solid black;
display:inline-block;
position:relative;
width:1024px;
height:768px;
overflow:hidden;
box-sizing:border-box;
}
.tile{
position:relative;
vertical-align:top;
display:inline-block;
border-right:1px solid rgba(0, 0, 0, 0.5);
border-bottom:1px solid rgba(0, 0, 0, 0.5);
box-sizing:border-box;
}
.tile:after{
content:"";
background-color:#cc1c32;
width:6px;
height:6px;
position:absolute;
top:100%;
right:0px;
transform:translate(50%, -50%);
z-index:2;
line-height:1;
}
/*-- no grid --*/
.noGrid .tile{
border-right:0px solid rgba(0, 0, 0, 0.5);
border-bottom:0px solid rgba(0, 0, 0, 0.5);
}
.noGrid .tile:after{
content:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tileContainer">
</div>
I've tried CSS cursor property
How to create a cursor like this webpage
https://my.pottermore.com/patronus
You can create such effects using css and JavaScript:
var standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
var nav = (!document.all || window.opera);
var tmr = null;
var spd = 50;
var x = 0;
var x_offset = 5;
var y = 0;
var y_offset = 15;
document.onmousemove = get_mouse;
function get_mouse(e)
{
x = (nav) ? e.pageX : event.clientX+standardbody.scrollLeft;
y = (nav) ? e.pageY : event.clientY+standardbody.scrollTop;
x += x_offset;
y += y_offset;
beam(1);
}
function beam(n)
{
if(n<5)
{
document.getElementById('div'+n).style.top=y+'px'
document.getElementById('div'+n).style.left=x+'px'
document.getElementById('div'+n).style.visibility='visible'
n++;
tmr=setTimeout("beam("+n+")",spd);
}
else
{
clearTimeout(tmr);
fade(4);
}
}
function fade(n)
{
if(n>0)
{
document.getElementById('div'+n).style.visibility='hidden'
n--;
tmr=setTimeout("fade("+n+")",spd);
}
else clearTimeout(tmr);
}
body{
overflow-x:hidden;
}
.s1
{
position : absolute;
font-size : 10pt;
color : blue;
visibility: hidden;
}
.s2
{
position : absolute;
font-size : 18pt;
color : red;
visibility : hidden;
}
.s3
{
position : absolute;
font-size : 14pt;
color : gold;
visibility : hidden;
}
.s4
{
position : absolute;
font-size : 12pt;
color : lime;
visibility : hidden;
}
<div id="div1" class="s1">*</div>
<div id="div2" class="s2">*</div>
<div id="div3" class="s3">*</div>
<div id="div4" class="s4">*</div>
This code can be found at: http://www.javascriptkit.com/script/script2/sparkler.shtml
OR if you do not want to use any HTML elements for your mouse trails you can use the following CSS and JS:
var dots = [],
mouse = {
x: 0,
y: 0
};
var Dot = function() {
this.x = 0;
this.y = 0;
this.node = (function(){
var n = document.createElement("div");
n.className = "tail";
document.body.appendChild(n);
return n;
}());
};
Dot.prototype.draw = function() {
this.node.style.left = this.x + "px";
this.node.style.top = this.y + "px";
};
for (var i = 0; i < 12; i++) {
var d = new Dot();
dots.push(d);
}
function draw() {
var x = mouse.x,
y = mouse.y;
dots.forEach(function(dot, index, dots) {
var nextDot = dots[index + 1] || dots[0];
dot.x = x;
dot.y = y;
dot.draw();
x += (nextDot.x - dot.x) * .6;
y += (nextDot.y - dot.y) * .6;
});
}
addEventListener("mousemove", function(event) {
mouse.x = event.pageX;
mouse.y = event.pageY;
});
function animate() {
draw();
requestAnimationFrame(animate);
}
animate();
.tail {
position: absolute;
height: 6px; width: 6px;
border-radius: 3px;
background: tomato;
}
This Code Can be found at : https://codepen.io/falldowngoboone/pen/PwzPYv
I want to crop image in specific area, I made below example
it is work when the inner not been rotate
my problem is after rotate the inner, I don't get how to find correct sx,sy,sw,sh to crop
UPDATE
base on this answer fix the draw rotate image part, I update in fiddle.
but I still don't get how to find correct position to crop rotated image ...
https://jsfiddle.net/ve219z34/3/
var crop = function() {
var transformMediaBlock = $('.mediaBlock');
var transformCropInner = $('.transformCropInner');
var transformCropLimit = $('.transformCropLimit');
var canvasContainer = $('.canvasContainer')
var limitLeft = transformCropLimit.offset().left;
var limitTop = transformCropLimit.offset().top;
var limitRight = limitLeft + transformCropLimit.width();
var limitBottom = limitTop + transformCropLimit.height();
var imageRatio = transformMediaBlock.find('img')[0].naturalWidth/transformMediaBlock.find('img').width();
// draw rotate image
var deg2Rad = Math.PI/180;
var rotateDegree = -20;
$('<canvas/>',{'class':'rotate'}).appendTo($(canvasContainer));
var canvas = $('.canvasContainer canvas')[0];
var ctx = canvas.getContext("2d");
var width = 0;
var height = 0;
var diagonal = 0;
var angleInDegrees = 0;
width = transformMediaBlock.find('img')[0].naturalWidth;
height = transformMediaBlock.find('img')[0].naturalHeight;
diagonal = Math.sqrt(Math.pow(width,2)+Math.pow(height,2));
ctx.canvas.width = diagonal;
ctx.canvas.height = diagonal;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(diagonal/2,diagonal/2);
ctx.rotate(0*Math.PI/180);
ctx.drawImage(transformMediaBlock.find('img')[0],-width/2,-height/2);
ctx.restore();
var drawRotated = function(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(diagonal/2,diagonal/2);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(transformMediaBlock.find('img')[0],-width/2,-height/2);
ctx.restore();
};
drawRotated(rotateDegree);
// problem is here don't know how to get correct sx sy sw sh with image been rotate
// draw crop rotate image
var imageLeft = transformMediaBlock.find('img').offset().left;
var imageTop = transformMediaBlock.find('img').offset().top;
var imageRight = imageLeft + transformMediaBlock.find('img').width();
var imageBottom = imageTop + transformMediaBlock.find('img').height();
if (limitLeft <= imageLeft) {
var sx = 0;
} else {
var sx = limitLeft - imageLeft;
}
if (limitTop <= imageTop) {
var sy = 0;
} else {
var sy = limitTop - imageTop;
}
if (limitLeft <= imageLeft) {
var l = imageLeft;
} else {
var l = limitLeft;
}
if (limitRight <= imageRight) {
var r = limitRight;
} else {
var r = imageRight;
}
var sw = r - l;
if (limitTop <= imageTop) {
var t = imageTop;
} else {
var t = limitTop;
}
if (limitBottom <= imageBottom) {
var b = limitBottom;
} else {
var b = imageBottom;
}
var sh = b - t;
sx = sx*imageRatio;
sy = sy*imageRatio;
sw = sw*imageRatio;
sh = sh*imageRatio;
var dx = 0;
var dy = 0;
var dw = sw;
var dh = sh;
};
$('#container').on('click', '.action.crop', function (e) {
var transformMediaBlock = $('.mediaBlock');
transformMediaBlock.find('img').on('load', function() {
$('.transformCropInner').addClass('rotate');
crop();
}).each(function() {
if(this.complete) $(this).load();
});
});
.mediaBlock {
position: relative;
display: block;
overflow: hidden;
}
.mediaBlock img {
max-width: 100%;
}
.transformCropLimit {
position: relative;
top: 20px;
left: 20px;
width: 200px;
height: 200px;
border: 1px solid blue;
}
.transformCropInner {
width: 100px;
cursor: pointer;
position: relative;
top: 10px;
left: 100px;
}
.transformCropInner.rotate {
transform: rotate(9-2deg);
-ms-transform: rotate(-20deg); /* IE 9 */
-moz-transform: rotate(-20deg); /* Firefox */
-webkit-transform: rotate(-20deg); /* Safari and Chrome */
-o-transform: rotate(-20deg); /* Opera */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<div class="canvasContainer"></div>
<div class="content main">
<div class="action crop">Crop</div>
<div class="transformCropLimit">
<div class="transformCropInner">
<div class="mediaBlock">
<img src="http://image.vsco.co/1/55210eb4aceed3144059/57f2471df662677e548b4568/300x400/25e7b55c-6ed9-490c-95c2-6d69520eb7bd1835072132.jpg">
</div>
</div>
</div>
</div>
</div>
Please don't provide plugin as an answer, and css crop is not what I'm looking for.
I am not sure why my move function, is not changing the style.left or style.top attributes of my 'toy'
Any tips, or general information/links on how to animate a div? I'm pulling my hair out over here. :)
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
//var moveX = math.random() * velocity;
//var moveY = math.random() * velocity;
function init() {
alert("in init fucntion");
ref = document.getElementById("toy");
alert("ref = " + ref.valueOf());
timer = setInterval(move, 50);
}
function move() {
alert("called move");
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
alert("left = " + left.valueOf() + " top = " + top.valueOf());
left += 5;
top += 5;
alert("left =" + left.valueOf() + "top = " + top.valueOf());
ref.style.left += left;
ref.style.top += 5;
alert("ref.style.left = " + ref.style.left.valueOf() + " ref.style.top = " + ref.style.top.valueOf());
ref.style.left = (left + deltaX) % posEnd;
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}
<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>
You just need to specify the units the position is in. For example, style.left = 10 won't work - you need style.left = '10px';
Here is a slightly simplified version of your move() function showing this:
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
And a fully working snippet:
var ref;
var timer;
var velocity = 50;
var deltaX = 5;
var deltaY = 5;
var left = 0;
var top = 0;
function init() {
ref = document.getElementById("toy");
timer = setInterval(move, 500);
}
function move() {
var left = parseInt(ref.style.left);
var top = parseInt(ref.style.top);
left += 5;
top += 5;
ref.style.left = left + 'px';
ref.style.top = top + 'px';
}
var posEnd = 0;
var objWidth = 100;
if (window.innerWidth) {
posEnd = window.innerWidth
} else if (window.document.body.clientWidth) {
posEnd = window.document.body.clientWidth
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body onload="init()">
<div style="width: 100px; height: 100px; position:absolute; left: 0px; top: 0px;" id="toy">
<img src="http://images.all-free-download.com/images/graphiclarge/mouse_clip_art_6054.jpg" style="max-height: 100%; max-width: 100%;">
</div>
</body>
</html>