Adding an element to not be overlapped - javascript

I've read this question about how to randomly position elements, and it works perfectly.
Positioning multiple, random sized, absolutely positioned elements so they don't overlap
How do I make the circles to not overlap the logo in the center when they position themselves randomly?
JSFiddle: http://jsfiddle.net/2h8783ba/
var maxSearchIterations = 10;
var min_x = 110;
var max_x = window.innerWidth - 310;
var min_y = 110;
var max_y = window.innerHeight - 310;
var filled_areas = [];
function calc_overlap(a1) {
var overlap = 0;
for (i = 0; i < filled_areas.length; i++) {
var a2 = filled_areas[i];
// no intersection cases
if (a1.x + a1.width < a2.x) {
continue;
}
if (a2.x + a2.width < a1.x) {
continue;
}
if (a1.y + a1.height < a2.y) {
continue;
}
if (a2.y + a2.height < a1.y) {
continue;
}
// intersection exists : calculate it !
var x1 = Math.max(a1.x, a2.x);
var y1 = Math.max(a1.y, a2.y);
var x2 = Math.min(a1.x + a1.width, a2.x + a2.width);
var y2 = Math.min(a1.y + a1.height, a2.y + a2.height);
var intersection = ((x1 - x2) * (y1 - y2));
overlap += intersection;
}
return overlap;
}
function randomize() {
filled_areas.splice(0, filled_areas.length);
var index = 0;
$('.c1, .c2, .c3, .c4').each(function() {
var rand_x = 0;
var rand_y = 0;
var i = 0;
var smallest_overlap = 9007199254740992;
var best_choice;
var area;
for (i = 0; i < maxSearchIterations; i++) {
rand_x = Math.round(min_x + ((max_x - min_x) * (Math.random() % 1)));
rand_y = Math.round(min_y + ((max_y - min_y) * (Math.random() % 1)));
area = {
x: rand_x,
y: rand_y,
width: $(this).width(),
height: $(this).height()
};
var overlap = calc_overlap(area);
if (overlap < smallest_overlap) {
smallest_overlap = overlap;
best_choice = area;
}
if (overlap === 0) {
break;
}
}
filled_areas.push(best_choice);
$(this).css({
position: "absolute",
"z-index": index++
});
$(this).animate({
left: rand_x,
top: rand_y
});
});
return false;
}

Here is the solution.
Css
#logo-content{
position: absolute;
left: 50%;
margin-left: -100px;
top: 50%;
margin-top: -100px;
z-index: 10;
}
Html
<div id="wrapper">
<div id="logo-content">
<svg version="1.1" id="logo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 93.7 93.7" enable-background="new 0 0 93.7 93.7" xml:space="preserve"></svg>
<div>
</div>

Related

Pointing arrow on precise location on donut chart

I am trying to point to certain parts on a donut chart. The chart is divided into 9 parts.
comArray is the main array which contain all parts. angleArray is the angles in degrees for each part. useArray contains the parts that should be located through the pointer.
My code is working for sometime but then it starts locating on some different point. For example, if pointer needs to point to 3 it locates properly but after 1 hour it will start locating on the 6 part for 3 part.
What I am doing wrong? You can check the working example here: https://bishttech.com/newtest/
$(document).ready(function() {
var comArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // main array of all parts
var angleArray = [20, 60, 100, 140, 180, 220, 260, 300, 340]; // angle in degrees for all parts
var useArray = [3, 6, 8, 2]; // pointer should stop on these parts
//console.log(areacount);
var canvas = document.getElementById("chart");
var ctx = canvas.getContext("2d");
function drawMultiRadiantCircle(xc, yc, r, radientColors) {
var partLength = (2 * Math.PI) / radientColors.length;
var start = 0;
var gradient = null;
var startColor = null,
endColor = null;
var startAngle = 0;
for (var i = 0; i < radientColors.length; i++) {
startColor = radientColors[i];
// endColor = radientColors[(i + 1) % radientColors.length];
endColor = adjust(startColor, -30);
// x start / end of the next arc to draw
var xStart = xc + Math.cos(start) * r;
var xEnd = xc + Math.cos(start + partLength) * r;
// y start / end of the next arc to draw
var yStart = yc + Math.sin(start) * r;
var yEnd = yc + Math.sin(start + partLength) * r;
ctx.beginPath();
gradient = ctx.createLinearGradient(xStart, yStart, xEnd, yEnd);
gradient.addColorStop(0, endColor);
gradient.addColorStop(0.5, startColor);
gradient.addColorStop(1.0, endColor);
ctx.strokeStyle = gradient;
ctx.arc(xc, yc, r, start, start + partLength);
ctx.lineWidth = 30;
ctx.stroke();
ctx.closePath();
start += partLength;
startAngle = partLength;
}
}
var someColors = ["#fb4168", "#4efb7f", "#fbf672", "#63e0fb", "#5b5bfb", "#f079fb", "#e0dffb", "#1aa3fb", "#1aa3fb"];
drawMultiRadiantCircle(300, 300, 200, someColors);
// get location of value
function getCurLoc(value) {
for (var i = 0; i < comArray.length; i++) {
if (value == comArray[i]) {
return i;
break;
}
}
}
var startingPnt = 0;
var curangleDegrees = 0;
var prevangleDegrees = 0;
var prevLoc = 0;
var curLoc = 0;
var rotateNum = 0;
var diffLoc = 0;
//function for displaying data on chart
function displayData() {
var maxPnt = useArray.length - 1;
var currentValue = useArray[startingPnt];
var getLoc = getCurLoc(currentValue); // getting location of value in comArray
if (rotateNum == 0) {
curangleDegrees = angleArray[getLoc];
curLoc = getLoc;
} else {
curLoc = getLoc;
diffLoc = curLoc - prevLoc;
curangleDegrees = (diffLoc * 40);
}
$(".img").rotate(curangleDegrees, {
easing: 'easeInExpo'
});
console.log(getLoc);
if (startingPnt == maxPnt) {
startingPnt = 0;
} else {
startingPnt++;
}
prevLoc = curLoc;
prevangleDegrees = curangleDegrees;
rotateNum++;
}
setInterval(function() {
displayData();
}, 10000);
function adjust(color, amount) {
return '#' + color.replace(/^#/, '').replace(/../g, color => ('0' + Math.min(255, Math.max(0, parseInt(color, 16) + amount)).toString(16)).substr(-2));
}
});
.img {
margin: 48px 52px;
position: absolute;
z-index: 1;
}
#container {
width: 50%;
display: block;
margin: 0 auto;
position: relative;
}
#chart {
position: relative;
z-index: 20;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="container">
<img class='img' src="images/arrowcircle.png" alt="" />
<canvas id="chart" width="800" height="800"></canvas>
</div>

Move to Mouse Click in SVG path (d3.js)

I need to create a circle and move it to the closest point in an SVG path on mousedown event
here is the jsfiddle
The Code:
var points = [[180,300],[234,335],[288,310],[350,290],[405,300],[430,305],[475,310],[513,300],[550,280]];
var width = 1000, height = 600;
var line = d3.svg.line().interpolate("cardinal");
var svg = d3.select("#Con").append("svg").attr("width", width).attr("height", height);
var path = svg.append("path").datum(points).attr("d", line);
var line = svg.append("line");
var circle = svg.append(" circle").attr("cx", -10).attr("cy", -10).attr("r", 3.5);
svg.append("rect").attr("width", width).attr("height", height).on("mousedown", mouseclick);
function mouseclick() {
var m = d3.mouse(this),p = closestPoint(path.node(), m);
circle.attr("cx", p[0]).attr("cy", p[1]);
}
function closestPoint(pathNode, point) {
var pathLength = pathNode.getTotalLength(),precision = 8,best,bestLength,bestDistance = Infinity;
for (var scan, scanLength = 0, scanDistance; scanLength <= pathLength; scanLength += precision) {
if ((scanDistance = distance2(scan = pathNode.getPointAtLength(scanLength))) < bestDistance) {
best = scan, bestLength = scanLength, bestDistance = scanDistance;
}
}
precision /= 2;
while (precision > 0.5) {
var before,after,beforeLength,afterLength,beforeDistance,afterDistance;
if ((beforeLength = bestLength - precision) >= 0 && (beforeDistance = distance2(before = pathNode.getPointAtLength(beforeLength))) < bestDistance) {
best = before, bestLength = beforeLength, bestDistance = beforeDistance;
} else if ((afterLength = bestLength + precision) <= pathLength && (afterDistance = distance2(after = pathNode.getPointAtLength(afterLength))) < bestDistance) {
best = after, bestLength = afterLength, bestDistance = afterDistance;
} else {
precision /= 2;
}
}
best = [best.x, best.y];
best.distance = Math.sqrt(bestDistance);
return best;
function distance2(p) {
var dx = p.x - point[0],dy = p.y - point[1];
return dx * dx + dy * dy;
}
}
I need to move the circle to the closest point in the path when I click in the SVG space
In my code the circle moves without animation and I need to animate it so that it moves on the path from point to point
I need it to always move with one speed whether it moves a large or small distance
like this:
https://a.top4top.net/p_11885szd41.gif
I'm not using your code but I hope you'll get the idea.
Instead of using a circle I'm using the track:
<use id="theUse" xlink:href="#track"
This track has a stroke-dasharray of ".1 398.80" This means a dash of .1 (very very small) and a gap of 398.80 as long as the track. The stroke-width is 7 with stroke-linecap= "round"and this is transforming the dash into a circle. I'm changing the position of the dash (the circle) using stroke-dashoffset and in order to animate the change I'm using transition: stroke-dashoffset 1s;in the css.
I hope it helps.
let m;
let L = track.getTotalLength();
let _start = {x:180,y:30}
let _end = {x:550,y:280}
let l = dist(_start, _end);
theUse.setAttributeNS(null,"stroke-dashoffset",L);
svg.addEventListener("click",(e)=>{
m = oMousePosSVG(e)
let pos = m.x - _start.x;
let theDistance = map(pos,_start.x,_end.x,0,L)
let s_dof = constrain(L-theDistance, .5, L-.5)
theUse.setAttributeNS(null,"stroke-dashoffset",s_dof)
})
function oMousePosSVG(e) {
var p = svg.createSVGPoint();
p.x = e.clientX;
p.y = e.clientY;
var ctm = svg.getScreenCTM().inverse();
var p = p.matrixTransform(ctm);
return p;
}
function dist(p1, p2) {
let dx = p2.x - p1.x;
let dy = p2.y - p1.y;
return Math.sqrt(dx * dx + dy * dy);
}
function map(n, a, b, _a, _b) {
let d = b - a;
let _d = _b - _a;
let u = _d / d;
return _a + n * u;
}
function constrain(n, low, high) {
return Math.max(Math.min(n, high), low);
};
svg {
border: 1px solid;
}
path {
fill: none;
}
#theUse {
transition: stroke-dashoffset 1s;
}
<svg id="svg" viewBox="150 250 450 100">
<defs>
<path id="track" d="M180,300Q223.2,334,234,335C250.2,336.5,270.6,316.75,288,310S332.45,291.5,350,290S393,297.75,405,300S419.5,303.5,430,305S462.55,310.75,475,310S501.75,304.5,513,300Q520.5,297,550,280"></path>
</defs>
<use xlink:href="#track" stroke="black" />
<use id="theUse" xlink:href="#track" stroke-width="7" stroke-dasharray = ".1 398.80" stroke="red" stroke-linecap= "round" />
</svg>
This answer modifies your code to move a circle from the start of the line or from the last mouse click to the current mouse click. It animates the movement of the circle by calling an animate method with setTimeout until the circle has moved from the beginning of the line to the point where the mouse was clicked.
The interesting code is here:
// getAnimate returns a function that is within a closure
function getAnimate(pLength, path, currentIndex, finishPos, forward){
let animate = function (){
let scan = path.node().getPointAtLength(currentIndex);
if (scan.x < finishPos || !forward && scan.x > finishPos){
circle.attr("cx", scan.x).attr("cy", scan.y);
}
if (forward){
currentIndex += 1;
lastIndex = currentIndex;
if (scan.x < finishPos){
setTimeout(animate, 50);
}
} else {
currentIndex -= 1;
lastIndex = currentIndex;
if (scan.x > finishPos){
setTimeout(animate, 50);
}
}
}
return animate;
}
var points = [[80,100],[134,115],[188,130],[250,120],[305,120],[330,101],[375,103],[413,100],[550,90]];
var width = 500, height = 200;
var line = d3.svg.line().interpolate("cardinal");
var svg = d3.select("#Con").append("svg").attr("width", width).attr("height", height);
var path = svg.append("path").datum(points).attr("d", line);
var line = svg.append("line");
var circle = svg.append("circle").attr("cx", -10).attr("cy", -10).attr("r", 3.5);
svg.append("rect").attr("width", width).attr("height", height).on("mousedown", mouseclick);
var lastIndex = 0;
function mouseclick() {
let m = d3.mouse(this);
let p = closestPoint(path.node(), m);
let forward = true;
let currentPoint = path.node().getPointAtLength(lastIndex);
if (p[0] < currentPoint.x){
forward = false;
}
let pathLength = path.node().getTotalLength();
getAnimate(pathLength, path, lastIndex, p[0], forward)();
}
function getAnimate(pLength, path, currentIndex, finishPos, forward){
let animate = function (){
let scan = path.node().getPointAtLength(currentIndex);
if (scan.x < finishPos || !forward && scan.x > finishPos){
circle.attr("cx", scan.x).attr("cy", scan.y);
}
if (forward){
currentIndex += 1;
lastIndex = currentIndex;
if (scan.x < finishPos){
setTimeout(animate, 50);
}
} else {
currentIndex -= 1;
lastIndex = currentIndex;
if (scan.x > finishPos){
setTimeout(animate, 50);
}
}
}
return animate;
}
function closestPoint(pathNode, point) {
var pathLength = pathNode.getTotalLength(),precision = 8,best,bestLength,bestDistance = Infinity;
for (var scan, scanLength = 0, scanDistance; scanLength <= pathLength; scanLength += precision) {
if ((scanDistance = distance2(scan = pathNode.getPointAtLength(scanLength))) < bestDistance) {
best = scan, bestLength = scanLength, bestDistance = scanDistance;
}
}
precision /= 2;
while (precision > 0.5) {
var before,after,beforeLength,afterLength,beforeDistance,afterDistance;
if ((beforeLength = bestLength - precision) >= 0 && (beforeDistance = distance2(before = pathNode.getPointAtLength(beforeLength))) < bestDistance) {
best = before, bestLength = beforeLength, bestDistance = beforeDistance;
} else if ((afterLength = bestLength + precision) <= pathLength && (afterDistance = distance2(after = pathNode.getPointAtLength(afterLength))) < bestDistance) {
best = after, bestLength = afterLength, bestDistance = afterDistance;
} else {
precision /= 2;
}
}
best = [best.x, best.y];
best.distance = Math.sqrt(bestDistance);
return best;
function distance2(p) {
var dx = p.x - point[0],dy = p.y - point[1];
return dx * dx + dy * dy;
}
}
* {
margin: 0;
padding: 0;
}
#Con {
border: 1px solid black;
margin: auto;
width: 1000px;
height: 600px;
}
#Map{
z-index: -1000;
position: absolute;
}
#Cha {
position: absolute;
}
path {
z-index: 1000;
fill: none;
stroke: #000;
stroke-width: 1.5px;
}
line {
fill: none;
stroke: red;
stroke-width: 1.5px;
}
circle {
fill: red;
}
rect {
fill: none;
pointer-events: all;
}
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.5.0"></script>
<div id="Con"></div>

trail without a canvas

I've created the following code and I would like to have a trail following the dropped ball.
JSFiddle: https://jsfiddle.net/uj896hmq/72/
Code
var generateGame = function(){
var string = "";
var discAmount = 0;
for(var x = 0; x < 13; x++){
discAmount++;
string += "<div class='row'>";
for(var y = 1; y <= discAmount; y++){
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function(){
startGame();
});
var startGame = function(){
var $board = $('.board .wrapper'),
$el = $(".falling");
var currentRow = 0,
path = generatePath();
setInterval(function(){
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow]),
top = getPosition.position().top,
left = getPosition.position().left;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}, 500);
}
var generatePath = function(){
var path = [0];
for(var x = 1; x < 13; x++){
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(generatePath());
Point is I have no idea how I would achieve this with regular javascript and or jQuery, I thought of maybe placing a lot of divs at the position of the ball but that didn't seem proper.
Anyone has any ideas?
You can use SVG to dynamically add lines to the HTML without canvas. I've created a crude example that you can refer to. Basically it is just some calculations to position the lines.
var generateGame = function() {
var string = "";
var discAmount = 0;
for (var x = 0; x < 13; x++) {
discAmount++;
string += "<div class='row'>";
for (var y = 1; y <= discAmount; y++) {
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function() {
startGame();
});
var startGame = function() {
var $board = $('.board .wrapper'),
$el = $(".falling"),
$trail = $('.trail'),
$prevDisc = null;
var currentRow = 0,
path = generatePath();
$trail.empty();
setInterval(function() {
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow])
if (getPosition.length > 0) {
var top = getPosition.position().top,
left = getPosition.position().left;
if ($prevDisc) {
var isLeft = left < $prevDisc.position().left;
drawPath($prevDisc.position().left, currentRow - 1, isLeft);
}
$prevDisc = getPosition;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}
}, 500);
}
var generatePath = function() {
var path = [0];
for (var x = 1; x < 13; x++) {
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function drawPath(xPos, prevRow, isLeft) {
if (prevRow >= 0) {
var svgTopOffSet = 12;
var svgHeight = 22;
var svgWidth = 22;
var $trail = $('.trail');
var $newTrail = $(document.createElementNS('http://www.w3.org/2000/svg', 'svg'));
$newTrail.attr({
x: xPos,
y: prevRow * svgHeight + svgTopOffSet
});
var $line = $(document.createElementNS('http://www.w3.org/2000/svg', 'line'));
$line.attr({
x1: svgWidth / 2,
y1: 0,
x2: isLeft ? 0 : svgWidth,
y2: svgWidth,
style: 'stroke:orange;stroke-width:3'
});
$newTrail.append($line);
$trail.append($newTrail);
}
}
body {
background: rgb(26, 30, 35);
}
.board {
width: 500px;
height: 300px;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
.row {
display: flex;
justify-content: center;
}
.row .disc {
height: 6px;
width: 6px;
border-radius: 50%;
background: gray;
margin: 8px;
}
.wrapper .falling {
position: absolute;
height: 11px;
width: 11px;
border-radius: 50%;
background: orange;
transform: translate(50%, 50%);
z-index: 1;
}
.wrapper {
position: relative;
}
.trail {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
line { stroke-dasharray: 25; stroke-dashoffset: 25; animation: offset 0.5s linear forwards; }
#keyframes offset {
to {
stroke-dashoffset: 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='board'>
<div class='wrapper'>
<svg class="trail">
</svg>
</div>
<button>
test game
</button>
</div>

Drawing squares within squares in JS

I am trying to run a script to draw a pattern of squares within squares.
var bodyNode = document.getElementsByTagName("body")[0];
var width = 600, height = 600;
var top = 10, left = 10;
while(width > 30) {
var divNode = document.createElement("div");
divNode.style.position = "absolute";
divNode.style.marginLeft = left;
divNode.style.marginTop = top;
divNode.style.width = width;
divNode.style.height = height;
divNode.style.background = randomColor();
bodyNode.appendChild(divNode);
width -= 10;
height -= 10;
top += 10;
left += 10;
}
function randomColor()
{
var color = "#";
for(var i =0; i < 6; i++)
{
var number = Math.floor(Math.random() * 10);
color += number;
}
return color;
}
But the properties which get added to the div are:
{
position: absolute;
margin-left: 260px;
width: 350px;
height: 350px;
background: rgb(88, 88, 5);
}
I am trying to achieve this pattern but I get a different pattern as shown in the image below.
What am I missing?
you are missing "px" suffix of Top,Left,Width,Height
See your corrected code here - https://jsfiddle.net/jw2rohr5/
Your corrected code -
var bodyNode = document.getElementsByTagName("body")[0];
var width = 600, height = 600;
var top = 10, left = 10;
while(width > 30)
{
var divNode = document.createElement("div");
divNode.style.position = "absolute";
divNode.style.marginLeft = left + "px";
divNode.style.marginTop = top + "px";
divNode.style.width = width + "px";
divNode.style.height = height + "px";
divNode.style.background = randomColor();
bodyNode.appendChild(divNode);
width -= 10;
height -= 10;
top += 10;
left += 10;
}
function randomColor()
{
var color = "#";
for(var i =0; i < 6; i++)
{
var number = Math.floor(Math.random() * 10);
color += number;
}
return color;
}
You should give suffix like "%","px" etc..
Try
body{
position: relative;
}
When the content have a position by default(static) the margin of node children not work correctly

Changing a div attribute using a function?

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>

Categories

Resources