I have the logic but I'm confused how to implement it.
The pseudo code of what I need to do is the following:
There is an image array and a counter, set to 0;
1 - When the cursor is initialized, start an interval timer and
monitor the mouse coordinates
2 - When the timer reaches the first interval, display the first image of the array at the actual coordinates of the mouse. Increment the counter.
3 - When the timer reaches the second interval, display the second image of the array at the actual coordinates of the mouse. Increment the counter.
Repeat the task for all images
If the counter == the image array length, reset the counter and start the process again.
For now I have this boilerplate:
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let activeCounter = 0;
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('img');
s.src= imgArray[activeCounter]
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
Ideally I'm going to make it in react.js but a plain vanilla JavaScript solution would help me in understanding the code implementation.
Thanks in advance.
If you move the setInterval outside, have the updated x, y values. Try this.
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let index = 0;
let imgArrayLength = imgArray.length;
let x = 0;
let y = 0;
function getMouseCoords(e) {
var e = e || window.event;
x = e.clientX;
y = e.clientY;
document.getElementById('info').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
setInterval(() => {
var img = document.createElement('img');
img.src = imgArray[(index++) % imgArrayLength];
img.style.position = "absolute";
img.style.left = x;
img.style.top = y;
document.getElementById('container').append(img);
}, 2000
);
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = "🚀"
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="info"></div>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let count = 0
let index = 0;
let imgArrayLength = imgArray.length;
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = "🚀"
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
setInterval(() => {
var s = document.createElement('div');
s.style.position = 'fixed';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '3px solid blue';
s.style.top = (e.clientX - 5) + 'px';
s.style.left = (e.clientY - 5) + 'px';
s.style.background = 'blue';
s.style['background-image'] = 'url(imgArray[count])'
document.getElementById('container').appendChild(s)
count++
if(imgArray.length === count)
count = 0
// set the img to position
}, 10000)
}
};
}());
window.onload = function() {
followCursor.init();
document.body.mouseenter = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
I hope this is what you are expecting...
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let activeCounter = 0;
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('img');
s.id = "imgid"
s.src= imgArray[activeCounter]
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
setInterval(() => {
activeCounter++
let s = document.getElementById('imgid');
s.src = imgArray[activeCounter]
if(imgArray.length === activeCounter)
activeCounter = 0
// set the img to position
}, 1000)
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
Related
inside the squareGenerator() function I create a yellow square every 1000 milliseconds. But I want each square to fall from the top of the screen to the very bottom, I want to do this in the fallingFunction(), something like what you would see in the "Guitar Hero" video game, where the notes fall down. Thank you.
//Square Generation
var allSquares = [];
var idGenerated = 0;
function squareGenerator() {
var newSquare = $(document.createElement("div"));
newSquare.css({
"background-color": "yellow",
"height": "200px",
"width": "200px",
"position": "absolute"
});
newSquare.attr('id', idGenerated);
idGenerated++;
allSquares.push(newSquare);
$('.father').append(newSquare);
}
var squareGenerationInterval = setInterval(squareGenerator, 1000);
//Square Falling
function fallingFunction() {
$("#" + idGenerated).css({"margin-top": "100px",});
}
var squareGenerationInterval = setInterval(fallingFunction, 1000);
body {
padding: 0;
margin: 0;
}
.father {
width: 100%;
height: 1000px;
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NovaNote</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="father">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
</body>
</html>
This is easy, you can use JQuery Animate. Although the code does need to be customized in other places in order to work.
First, let's add a parameter to fallingFunction which is square.
function fallingFunction(square) {
square.animate(
// Styles
{"margin-top": "100px"},
// Speed in miliseconds
5000);
}
This basically just animates the margin-top to 100px.
Second, remove the interval that calls fallingFunction.
So delete var squareGenerationInterval = setInterval(fallingFunction, 1000);.
Now you'll have to edit your square ids because #0 is not accepted, try something like #square0.
newSquare.attr('id', 'square' + idGenerated);
And Finnaly, you can call fallingFunction after $('.father').append(newSquare); passing in the newSquare object. Call it like this: fallingFunction(newSquare);.
So this is how your code should look like:
//Square Generation
var allSquares = [];
var idGenerated = 0;
function squareGenerator() {
var newSquare = $(document.createElement("div"));
newSquare.css({
"background-color": "yellow",
"height": "200px",
"width": "200px",
"position": "absolute"
});
newSquare.attr('id', 'square' + idGenerated);
idGenerated++;
allSquares.push(newSquare);
$('.father').append(newSquare);
fallingFunction(newSquare);
}
var squareGenerationInterval = setInterval(squareGenerator, 1000);
//Square Falling
function fallingFunction(sqaure) {
sqaure.animate(
// Styles
{"margin-top": "100px"},
// Speed in miliseconds
5000);
}
body {
padding: 0;
margin: 0;
}
.father {
width: 100%;
height: 1000px;
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NovaNote</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="father">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
</body>
</html>
I used CSS keyframes and some additional CSS to achieve this.
//Square Generation
var allSquares = [];
var idGenerated = 0;
function squareGenerator() {
// if (idGenerated < 5) return false;
var newSquare = $(document.createElement("div"));
newSquare.css({
"background-color": idGenerated % 2 === 0 ? 'green' : 'blue',
"height": "200px",
"width": "200px",
"position": "absolute"
});
newSquare.attr('class', 'sq'); // add class
newSquare.attr('id', idGenerated);
idGenerated++;
allSquares.push(newSquare);
$('.father').append(newSquare);
}
var squareGenerationInterval = setInterval(squareGenerator, 1000);
// comment out not needed
//Square Falling
// function fallingFunction() {
// $("#" + idGenerated).css({"margin-top": "100px",});
// }
// var squareGenerationInterval = setInterval(fallingFunction, 1000);
body {
padding: 0;
margin: 0;
}
.father {
width: 100%;
height: 1000px;
background-color: lightblue;
}
#keyframes slidein {
from {
top: 0;
}
to {
top: calc(100% - 200px);
}
}
div.sq {
animation-name: slidein;
animation-duration: 2s;
animation-iteration-count: 1;
top: calc(100% - 200px);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NovaNote</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="father">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
</body>
</html>
http://jsfiddle.net/apHLu/4/
Use this as your reference, Every time the text is clicked, the div falls down..
Keeping this as reference, use a setTimeout function for a few seconds ( may be 1-2 seconds ) on your sqaureGenerator() function and put fallingFunction() as a callback function running the Reference Code to make the objects fall
I would use transition. I wouldn't use jQuery these days, since it's now easy to do nearly anything just as easily with raw JavaScript. Including a small library for reuse, here's a full example of what your code might look like:
//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, beacon, S, Q, hC, aC, rC, tC, shuffle, rand, DropBox;
addEventListener('load', ()=>{
get = (url, func, responseType = 'json', context = null)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url); x.responseType = responseType;
x.onload = ()=>{
if(func)func.call(c, x.response);
}
x.onerror = e=>{
if(func)func.call(c, {xhrErrorEvent:e});
}
x.send();
return x;
}
post = function(url, send, func, responseType ='json', context = null){
const x = new XMLHttpRequest;
if(typeof send === 'object' && send && !(send instanceof Array)){
const c = context || x;
x.open('POST', url); x.responseType = responseType;
x.onload = ()=>{
if(func)func.call(c, x.response);
}
x.onerror = e=>{
if(func)func.call(c, {xhrErrorEvent:e});
}
let d;
if(send instanceof FormData){
d = send;
}
else{
let s;
d = new FormData;
for(let k in send){
s = send[k];
if(typeof s === 'object' && s)s = JSON.stringify(s);
d.append(k, s);
}
}
x.send(d);
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
beacon = function(url, send){
let r = false;
if(typeof send === 'object' && send && !(send instanceof Array)){
let d;
if(send instanceof FormData){
d = send;
}
else{
let s;
d = new FormData;
for(let k in send){
s = send[k];
if(typeof s === 'object' && s)s = JSON.stringify(s);
d.append(k, s);
}
}
r = nav.sendBeacon(url, d);
}
else{
throw new Error('send argument must be an Object');
}
return r;
}
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = function(node, className){
return node.classList.contains(className);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
shuffle = array=>{
let a = array.slice(), i = a.length, n, h;
while(i){
n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
}
return a;
}
rand = (min, max)=>{
let mn = min, mx = max;
if(mx === undefined){
mx = mn; mn = 0;
}
return mn+Math.floor(Math.random()*(mx-mn+1));
}
DropBox = function(width, height, backgroundColor){
this.box = M('div');
let bs = this.box.style, w, h;
w = isNaN(width) ? width : width+'px';
h = isNaN(height) ? height : height+'px';
bs.width = w; bs.height = h; bs.position = 'absolute';
bs.backgroundColor = backgroundColor;
this.setPosition = (left = 0, top = 0)=>{
bs.left = isNaN(left) ? left : left+'px';
bs.top = isNaN(top) ? top : top+'px';
return this;
}
this.setPosition();
this.moveTo = (left = null, top = null, transition = 'left 1s ease-in-out, top 1s ease-in-out')=>{
let l = isNaN(left) || left === null ? left : left+'px';
let t = isNaN(top) || top === null ? top : top+'px';
bs.transition = transition;;
if(l === null && t === null){
bs.top = 'calc(100% - '+h+')';
}
else{
bs.left = l; bs.top = t;
}
return this;
}
}
// magic happens under here
const stage = I('stage'), yellow = new DropBox(50, 50, '#cc0');
const red = new DropBox('20px', '30', '#c00'), blue = new DropBox(25, 25, '#00c');
yellow.setPosition(50, 100); red.setPosition('calc(50% - 10px)');
stage.appendChild(yellow.box); stage.appendChild(red.box);
stage.appendChild(blue.box);
setTimeout(()=>{
red.moveTo(50, 100);
setTimeout(()=>{
yellow.moveTo();
setTimeout(()=>{
blue.moveTo();
}, 250);
}, 1000);
}, 500);
}); // end load
/* css/external.css */
*{
box-sizing:border-box; font:22px Tahoma, Geneva, sans-serif; color:#000; padding:0; margin:0; overflow:hidden;
}
html,body,#stage{
width:100%; height:100%;
}
#stage{
position:relative; background:#add8e6; overflow-y:auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div id='stage'></div>
</body>
</html>
You can start reading the JavaScript at // magic happens under here. Of course, the code uses the DropBox constructor that I've made for your reuse. By the way, if you require more versatility I would do animations with canvas.
I have a function that gets me the coordinates of the position of an image when you click on it. What I want to achieve is that when I click on the image draw a point in that same position as shown in the image:
this is my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://t1.up.ltmcdn.com/es/images/2/6/6/img_organos_internos_del_cuerpo_humano_lista_completa_1662_600.jpg" height="500" width="500" alt="dragon">
<script>
$(document).ready(function() {
$("img").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
alert("X Coordinate: " + x + " Y Coordinate: " + y);
});
});
</script>
Just append an absolutely positioned element to the coordinates:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://t1.up.ltmcdn.com/es/images/2/6/6/img_organos_internos_del_cuerpo_humano_lista_completa_1662_600.jpg" height="500" width="500" alt="dragon">
<script>
$(document).ready(function() {
const size = 4;
$("img").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
$(this).parent().append(`<div style="width: ${size}px; height: ${size}px; background: black; position: absolute; top: ${y + size}px; left: ${x + size}px; border-radius: ${size}px"/>`);
});
});
</script>
I would use raw JavaScript. I don't have time to fully explain right now, but may later. Good Luck!
//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, S, Q, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
// magic under here
const stage = I('stage'), human = I('human'), dot = M('div'), dotStyle = dot.style;
dot.id = 'dot';
let move = false;
function moveDot(e){
if(move === true){
let left = e.clientX, top = e.clientY;
if(!stage.contains(dot))stage.appendChild(dot);
dotStyle.left = left+'px'; dotStyle.top = top+'px';
}
}
if(mobile){
human.ontouchstart = (e)=>{
move = true; moveDot(e);
}
human.ontouchmove = moveDot;
human.ontouchend = ()=>{
move = false;
}
}
else{
human.onmousedown = e=>{
move = true; e.preventDefault(); moveDot(e);
}
human.onmousemove = moveDot;
human.onmouseup = ()=>{
move = false;
}
}
}); // end load
/* css/external.css */
*{
box-sizing:border-box;
}
html,body{
width:100%; height:100%; padding:0; margin:0; background:#ccc;
}
.main,#stage{
width:100%; height:100%;
}
#stage{
position:relative; height:100%;
}
#stage>*{
position:absolute;
}
#human{
height:100%; margin:auto; top:0; right:0; bottom;0; left:0;
}
#dot{
border:1px solid #009; border-radius:50%;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='stage'>
<img id='human' src='https://t1.up.ltmcdn.com/es/images/2/6/6/img_organos_internos_del_cuerpo_humano_lista_completa_1662_600.jpg' alt='dragon' />
</div>
</div>
</body>
</html>
I am trying to do three things with the following Pong game code:
Make the black line in the center dashed
Make the score bigger and in a different font
stop the paddles from going off the board
Here is the Html part:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title> Pong </title>
<link href="style.css" rel="stylesheet" type="text/css" />
<style>
body {background-color: pink;}
#canvas {
border: solid MediumTurquoise 0.5vw;
height: 50%;
width: 50%;
background-color: white;
}
.welcome{
font-family: 'monospace'
}
</style>
</head>
<body>
<div class = "welcome"> <center> <h2> Welcome to Pong! Good luck. <h2> </center> </div>
Here is how I started the canvas:
<center> <canvas id="canvas"></canvas> </center>
<score id ="left_score">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
<script>
/* initialize */
All of my variables:
var context = $('#canvas')[0];
var gameboard =context.getContext('2d');
var ball_x_speed = 1;
var ball_x_initial_speed = 1;
var ball_y_speed = 1;
var ball_width = 20;
var ball_height = 20;
var ball_x_initial =140;
var ball_y_initial = 65;
var ball_x = ball_x_initial;
var ball_y = ball_y_initial;
var paddle_y = 30;
var paddle_y_speed = 0;
var paddle_y_initial = 50;
var frames_per_second = 60;
var paddle_2 = 100;
var paddle_2_speed = 0;
var paddle_2_initial = 50;
var left_score = 0;
var right_score = 0;
Game board fill function that I used to insert the rectangles in the first place. I want to make the black one dashed.
gameboard.fillRect(10,paddle_y,5,50);
gameboard.fillRect (270,paddle_2,5,50);
gameboard.fillStyle ='magenta';
gameboard.fillStyle = 'yellowgreen';
gameboard.fillRect(ball_x,ball_y,ball_width,ball_height);
gameboard.setLineDash =(140,0,10,270)
setInterval(doSomething, 1000/frames_per_second);
$('body').on('keydown',move_paddle);
$('body').on('keyup',stop_paddle);
This function moves the paddles up and down. I want to stop them at the edges of my canvas.
function move_paddle(event){
if(event.which == 87){paddle_y_speed= -2;}
if(event.which == 83){paddle_y_speed = 2;}
if(event.which == 40){paddle_2_speed= 2;}
if(event.which == 38){paddle_2_speed = -2;}
}
function stop_paddle(){
paddle_y_speed = 0;
paddle_2_speed = 0;
};
function doSomething(){
gameboard.clearRect(0,0,300,150);
gameboard.fillStyle = 'magenta';
gameboard.fillRect(10,paddle_y,5,50);
gameboard.fillRect (270,paddle_2,5,50);
gameboard.fillStyle = 'black';
gameboard.fillRect(140,0,10,270)
/*end game */
if (ball_x <=0){
ball_x_speed = ball_x_initial_speed}
if (ball_x >=280){
ball_x_speed = ball_x_initial_speed}
if (left_score >=5){
alert ("Left player wins")
gameboard.fillRect(10,paddle_y,5,50);
gameboard.fillRect (270,paddle_2,5,50);
gameboard.fillStyle ='red';
gameboard.fillStyle = 'yellowgreen';
gameboard.fillRect(ball_x,ball_y,ball_width,ball_height);
}
/* bounce off walls */
if(ball_y >= 150-ball_height){ball_y_speed = -1*ball_y_speed;};
if(ball_y <=0){ball_y_speed = -1*ball_y_speed;};
if(ball_x >=300-ball_width){ball_x_speed = -1*ball_x_speed;};
if(ball_x <=0){
right_score = right_score + 1;
ball_x = ball_x_initial;
ball_y = ball_y_initial; }
if(ball_x >=280){
left_score = left_score + 1;
ball_x = ball_x_initial;
ball_y = ball_y_initial;
}
/* bounce off paddles */
if(ball_x <= 15 && ball_y <= paddle_y + 50 && ball_y >= paddle_y - 20){ball_x_speed = -1.25*ball_x_speed;};
if(ball_x >= 250 && ball_y <= paddle_2 + 50 && ball_y >= paddle_2 - 20){ball_x_speed = -1.25*ball_x_speed;}
ball_x = ball_x + ball_x_speed;
ball_y = ball_y + ball_y_speed;
paddle_y= paddle_y + paddle_y_speed
paddle_2= paddle_2 + paddle_2_speed
gameboard.fillStyle = 'yellowgreen';
gameboard.fillRect(ball_x,ball_y,ball_width,ball_width);
gameboard.fillStyle = 'red';
gameboard.fillText(left_score,120,20);
gameboard.fillText(right_score,160,20);
}
/*paddle goes off screen
if(paddle_2 <=0) {paddle_2 = paddle_2_initial} */
</script>
to make your line in the middle dashed, you can't simply replace the fillRect with setLineDash. This will only set a property of a line you have yet to draw. you can draw a dashed line like this for example:
gameboard.lineWidth = 5;
gameboard.beginPath();
gameboard.setLineDash([10, 10]);
gameboard.moveTo(140, 0);
gameboard.lineTo(140, 270);
gameboard.stroke();
To change the font of your score, you need to set the font property:
gameboard.font = "30px Arial";
And lastly, to make sure paddles don't go beyond your gameboard, a simple solution would be to just set them to the maximal/minimal allowed values when they go beyond:
paddle_y= paddle_y + paddle_y_speed
if (paddle_y < 0) paddle_y = 0;
if (paddle_y > 100) paddle_y = 100;
paddle_2= paddle_2 + paddle_2_speed
if (paddle_2 < 0) paddle_2 = 0;
if (paddle_2 > 100) paddle_2 = 100;
I want to do DRAG and REPLACE div in javascript. For Ex: I am having 2 Div's. If i drag the 2nd Div and place it on the 1st Div, automatically the 1st div should be replaced to the 2nd position. The code which i am having now is overlapping..
my aspx page..
<body>
<div id="container">
<div id="info">
Start drag process...</div>
<div id="square" style="position: relative; width: 60px; height: 60px; background: #990033;
border: 2px solid #3399CC;">
</div>
<div id="Div1" style="position: relative; width: 60px; height: 60px; background: #efe;
border: 2px solid #3399CC;">
</div>
<script type="text/javascript">
var square = DragHandler.attach(document.getElementById('square'));
var Div1 = DragHandler.attach(document.getElementById('Div1'));
</script>
</div>
my js file...
/**
*
* Crossbrowser Drag Handler
* http://www.webtoolkit.info/
*
**/
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
oElem.dragBegin(oElem, x, y);
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
oElem.drag(oElem, x, y);
return false;
},
// private method. Stop drag process.
_dragEnd : function() {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
oElem.dragEnd(oElem, x, y);
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
How to do this...
Here is the recognition part:
for (var i = 0; i < document.getElementsByClassName("draggable").length; i++) {
var elem = document.getElementsByClassName("draggable")[i];
if (elem != oElem) {
if (oElem.offsetTop + parseInt(oElem.style.height) > elem.offsetTop
&& oElem.offsetTop < elem.offsetTop + parseInt(elem.style.height)) {
if (oElem.offsetLeft + parseInt(oElem.style.width) > elem.offsetLeft
&& oElem.offsetLeft < elem.offsetLeft + parseInt(elem.style.width)) {
alert("overlapping");
}
}
}
}
Your div's need to have a "draggable" class.
Demo: http://jsfiddle.net/DqJrV/
var start_mouse_y = 0;
var scroll_offset = 0;
function SET_SCROLL(e){
document.getElementById("online_list_scroll").draggable = true;
start_mouse_y = e.clientY;
}
function ADJUST_SCROLL(e){
dont_pass = (412 - set_scroll_height);
mouse_y = e.clientY;
scroll_top = parseInt(document.getElementById("online_list_scroll").style.top);
scroll_offset = (mouse_y - scroll_top) + 46;
new_top = scroll_top + (mouse_y - start_mouse_y);
document.getElementById("DEBUG").innerHTML = "my: "+mouse_y+"<br>new_top: "+new_top+"<br>scroll_offset: "+scroll_offset+"<br>scroll_top: "+scroll_top;
if(new_top <= 0){
document.getElementById("online_list_scroll").style.top = 0+"px";
}else if(new_top >= dont_pass){
document.getElementById("online_list_scroll").style.top = dont_pass+"px";
}else{
document.getElementById("online_list_scroll").style.top = new_top+"px";
}
scroll_bottom = set_scroll_height + new_top;
scroll_percent = scroll_bottom / 412;
online_show = (document.getElementById("online_list").scrollHeight - 412) * scroll_percent;
online_show = Math.round(online_show);
document.getElementById("online_list").scrollTop = online_show;
}
var SCROLL_ON = 0;
document.onmouseup = function(){ SCROLL_ON = 0; };
document.onmousemove = function(event){ if(SCROLL_ON == 1){ADJUST_SCROLL(event);} };
javascript ^^
<div style="float: left; width: 13px; position: relative; height: 412px;">
<div id="online_list_scroll" style="width: 5px; position: absolute; top: 0px; left: 4px; border-radius: 4px; background-color: #3f3f3f; height: 15px;" onmousedown="if(SCROLL_ON == 0){ SET_SCROLL(event); SCROLL_ON = 1; }"></div>
</div>
html^^
i dont know why but the scroll bar scrolls at a very fast and unsteady flow rate. it works, but just jerks when scrolls up and down, jerk as in as u move one way it shoots that way quicker and quicker.
Thanks for any help, worked figuring out how to do this all night.
You have a problem with local var the following code works. Not made as a general thing, just repaired the code. Here you have the code with the comments where is the common mistake.
//first make sure you have defined with var the variables you need.
var start_mouse_y = 0;
var mouse_y = 0;
var scroll_offset = 0;
function SET_SCROLL(e) {
document.getElementById("online_list_scroll").draggable = true;
start_mouse_y = e.clientY;
// you need mouse_y to be initialized with start_mouse_y
mouse_y = start_mouse_y;
}
function ADJUST_SCROLL(e) {
var set_scroll_height = 0;
var dont_pass = (412 - set_scroll_height);
// here you set the last mouse_y to be start_mouse_y or else it would be
// a the first position of the mouse ( eg. 8 ) subtracted from the current ( eg. 50 )
// now remembering the last already added position (eg. 49) which is subtracted from
// the current (eg. 50 ) it works just fine
start_mouse_y = mouse_y;
mouse_y = e.clientY;
var scroll_top = parseInt(document.getElementById("online_list_scroll").style.top);
scroll_offset = (scroll_top- mouse_y ) + 46;
var new_top = scroll_top + (mouse_y- start_mouse_y);
console.log("my: " + mouse_y + "<br>new_top: " + new_top + "<br>scroll_offset: " + scroll_offset + "<br>scroll_top: " + scroll_top);
if(new_top <= 0) {
document.getElementById("online_list_scroll").style.top = 0 + "px";
} else if(new_top >= dont_pass) {
document.getElementById("online_list_scroll").style.top = dont_pass + "px";
} else {
document.getElementById("online_list_scroll").style.top = new_top + "px";
}
var scroll_bottom = set_scroll_height + new_top;
var scroll_percent = scroll_bottom / 412;
var online_show = (document.getElementById("online_list").scrollHeight - 412) * scroll_percent;
online_show = Math.round(online_show);
document.getElementById("online_list").scrollTop = online_show;
}
var SCROLL_ON = 0;
document.onmouseup = function() {
SCROLL_ON = 0;
};
document.onmousemove = function(event) {
if(SCROLL_ON == 1) {ADJUST_SCROLL(event);
}
};
Best regards,