How to make bottom wall rounded using canvas - javascript

I am working on ball2.js. I have draggable balls inside a box with 4 walls. Balls are draggable, pullable. I want to update me bottom straight wall to a little curve so it will looks like a bowl. Any help would be highly appreciated
BALL.JS (FILE)
var canvas;
let xyz = 1;
var delta = [ 0, 0 ];
var stage = [ window.screenX, window.screenY, window.innerWidth, window.innerHeight ];
getBrowserDimensions();
var themes = [ [ "#10222B", "#95AB63", "#BDD684", "#E2F0D6", "#F6FFE0" ],
]; // Here you can add/remove the theme colours.
var theme;
var worldAABB, world, iterations = 1, timeStep = 1 / 15;
var walls = [];
var wall_thickness = 200;
var wallsSetted = false;
var bodies, elements, text;
var createMode = false;
var destroyMode = false;
var isMouseDown = false;
var mouseJoint;
var mouse = { x: 0, y: 0 };
var gravity = { x: 0, y: 1 };
var PI2 = Math.PI * 2;
var timeOfLastTouch = 0;
init();
play();
function init() {
canvas = document.getElementById("canvas");
console.log(canvas);
canvas.style.borderTopLeftRadius = "20px";
// canvas.style[ 'backgroundColor' ] = "#000";
// var ctx = canvas.getContext("2d");
// ctx.fillStyle = "blue";
document.onmousedown = onDocumentMouseDown;
document.onmouseup = onDocumentMouseUp;
document.onmousemove = onDocumentMouseMove;
document.ondblclick = onDocumentDoubleClick;
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
document.addEventListener( 'touchend', onDocumentTouchEnd, false );
window.addEventListener( 'deviceorientation', onWindowDeviceOrientation, false );
// init box2d
worldAABB = new b2AABB();
worldAABB.minVertex.Set( -200, -200 );
worldAABB.maxVertex.Set( window.innerWidth + 200, window.innerHeight + 200 );
world = new b2World( worldAABB, new b2Vec2( 0, 0 ), true );
setWalls();
reset();
}
function play() {
setInterval( loop, 1000 / 40 );
}
function reset() {
var i;
if ( bodies ) {
for ( i = 0; i < bodies.length; i++ ) {
var body = bodies[ i ]
canvas.removeChild( body.GetUserData().element );
world.DestroyBody( body );
body = null;
}
}
// color theme
theme = themes[ Math.random() * themes.length >> 0 ];
// document.body.style[ 'backgroundColor' ] = "#e2e2e2";
bodies = [];
elements = [];
// createInstructions();
for( i = 0; i < 50; i++ ) {
createBall();
}
}
//
function onDocumentMouseDown() {
isMouseDown = true;
return false;
}
function onDocumentMouseUp() {
isMouseDown = false;
return false;
}
function onDocumentMouseMove( event ) {
mouse.x = event.clientX + 0;
mouse.y = event.clientY + 250;
}
function onDocumentDoubleClick() {
reset();
}
function onDocumentTouchStart( event ) {
if( event.touches.length == 1 ) {
event.preventDefault();
// Faking double click for touch devices
var now = new Date().getTime();
if ( now - timeOfLastTouch < 250 ) {
reset();
return;
}
timeOfLastTouch = now;
mouse.x = event.touches[ 0 ].pageX;
mouse.y = event.touches[ 0 ].pageY;
isMouseDown = true;
}
}
function onDocumentTouchMove( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
mouse.x = event.touches[ 0 ].pageX;
mouse.y = event.touches[ 0 ].pageY;
}
}
function onDocumentTouchEnd( event ) {
if ( event.touches.length == 0 ) {
event.preventDefault();
isMouseDown = false;
}
}
function onWindowDeviceOrientation( event ) {
if ( event.beta ) {
gravity.x = Math.sin( event.gamma * Math.PI / 180 );
gravity.y = Math.sin( ( Math.PI / 4 ) + event.beta * Math.PI / 180 );
}
}
//
function createInstructions() {
var size = 250;
var element = document.createElement( 'div' );
element.width = size;
element.height = size;
element.style.position = 'absolute';
element.style.left = -200 + 'px';
element.style.top = -200 + 'px';
element.style.cursor = "default";
canvas.appendChild(element);
elements.push( element );
var circle = document.createElement( 'canvas' );
circle.width = size;
circle.height = size;
var graphics = circle.getContext( '2d' );
graphics.fillStyle = theme[ 3 ];
graphics.beginPath();
graphics.arc( size * .5, size * .5, size * .5, 0, PI2, true );
graphics.closePath();
graphics.fill();
element.appendChild( circle );
text = document.createElement( 'div' );
text.onSelectStart = null;
text.innerHTML = '<span style="color:' + theme[0] + ';font-size:40px;">Hello!</span><br /><br /><span style="font-size:15px;"><strong>This is how it works:</strong><br /><br />1. Drag a ball.<br />2. Double click to change colors.<br />3. Shake your browser.<br />4. Click Background.<br />5. Play!</span>';
text.style.color = theme[1];
text.style.position = 'absolute';
text.style.left = '0px';
text.style.top = '0px';
text.style.fontFamily = 'Georgia';
text.style.textAlign = 'center';
element.appendChild(text);
text.style.left = ((250 - text.clientWidth) / 2) +'px';
text.style.top = ((250 - text.clientHeight) / 2) +'px';
var b2body = new b2BodyDef();
var circle = new b2CircleDef();
circle.radius = size / 2;
circle.density = 1;
circle.friction = 0.3;
circle.restitution = 0.3;
b2body.AddShape(circle);
b2body.userData = {element: element};
b2body.position.Set( Math.random() * stage[2], Math.random() * -200 );
b2body.linearVelocity.Set( Math.random() * 400 - 200, Math.random() * 400 - 200 );
bodies.push( world.CreateBody(b2body) );
}
function createBall( x, y ) {
// console.log(xyz);
xyz++;
if(xyz == 1){
var img = document.getElementById("coin1")
}else if(xyz == 2){
var img = document.getElementById("coin2")
}else if(xyz == 3){
var img = document.getElementById("coin3")
}else if(xyz == 4){
var img = document.getElementById("coin4")
}else if(xyz == 5){
var img = document.getElementById("coin5")
}else if(xyz == 6){
var img = document.getElementById("coin6")
}else if(xyz == 7){
var img = document.getElementById("coin7")
}else if(xyz == 8){
var img = document.getElementById("coin8")
}else if(xyz == 9){
var img = document.getElementById("coin9")
}else if(xyz == 10){
var img = document.getElementById("coin10")
}else if(xyz == 11){
var img = document.getElementById("coin11")
}else if(xyz == 12){
var img = document.getElementById("coin12")
}else if(xyz == 13){
var img = document.getElementById("coin13")
}else if(xyz == 14){
var img = document.getElementById("coin14")
}else if(xyz == 15){
var img = document.getElementById("coin15")
}else if(xyz == 16){
var img = document.getElementById("coin16")
}else if(xyz == 17){
var img = document.getElementById("coin17")
}else if(xyz == 18){
var img = document.getElementById("coin18")
}else if(xyz == 19){
var img = document.getElementById("coin19")
}else if(xyz == 20){
var img = document.getElementById("coin20")
}else if(xyz == 21){
var img = document.getElementById("coin21")
}else if(xyz == 22){
var img = document.getElementById("coin22")
}else if(xyz == 23){
var img = document.getElementById("coin23")
}else if(xyz == 24){
var img = document.getElementById("coin24")
}else if(xyz == 25){
var img = document.getElementById("coin25")
}else if(xyz == 26){
var img = document.getElementById("coin26")
}else if(xyz == 27){
var img = document.getElementById("coin27")
}else if(xyz == 28){
var img = document.getElementById("coin28")
}else if(xyz == 29){
var img = document.getElementById("coin29")
}else if(xyz == 30){
var img = document.getElementById("coin30")
}else if(xyz == 31){
var img = document.getElementById("coin31")
}else if(xyz == 32){
var img = document.getElementById("coin32")
}else if(xyz == 33){
var img = document.getElementById("coin33")
}else if(xyz == 34){
var img = document.getElementById("coin34")
}else if(xyz == 35){
var img = document.getElementById("coin35")
}else if(xyz == 36){
var img = document.getElementById("coin36")
}else if(xyz == 37){
var img = document.getElementById("coin37")
}else if(xyz == 38){
var img = document.getElementById("coin38")
}else if(xyz == 39){
var img = document.getElementById("coin39")
}else if(xyz == 40){
var img = document.getElementById("coin40")
}else if(xyz == 41){
var img = document.getElementById("coin41")
}else if(xyz == 42){
var img = document.getElementById("coin42")
}else if(xyz == 43){
var img = document.getElementById("coin43")
}else if(xyz == 44){
var img = document.getElementById("coin44")
}else if(xyz == 45){
var img = document.getElementById("coin45")
}else if(xyz == 46){
var img = document.getElementById("coin46")
}else if(xyz == 47){
var img = document.getElementById("coin47")
}else if(xyz == 48){
var img = document.getElementById("coin48")
}else if(xyz == 49){
var img = document.getElementById("coin49")
}
else{
var img = document.getElementById("coin50")
}
var x = x || Math.random() * stage[2];
var y = y || Math.random() * -200;
var size = (Math.random() * 100 >> 0) + 20;
var element = document.createElement("canvas");
element.width = size;
element.height = size;
element.style.position = 'absolute';
element.style.left = -200 + 'px';
element.style.top = -200 + 'px';
element.style.WebkitTransform = 'translateZ(0)';
element.style.MozTransform = 'translateZ(0)';
element.style.OTransform = 'translateZ(0)';
element.style.msTransform = 'translateZ(0)';
element.style.transform = 'translateZ(0)';
var graphics = element.getContext("2d");
var num_circles = Math.random();
for (var i = size; i > 0; i-= (size/num_circles)) {
graphics.drawImage(img,0,0, size , size);
graphics.arc(size * .5, size * .5, i * .5, 0, PI2, true);
canvas.appendChild(element);
elements.push( element );
// graphics.arc(size, size, i, 0, PI2, true);
// graphics.closePath();
// graphics.fill();
}
var b2body = new b2BodyDef();
var circle = new b2CircleDef();
circle.radius = size >> 1;
circle.density = 1;
circle.friction = 0.3;
circle.restitution = 0.3;
b2body.AddShape(circle);
b2body.userData = {element: element};
b2body.position.Set( x, y );
b2body.linearVelocity.Set( Math.random() * 400 - 200, Math.random() * 400 - 200 );
bodies.push( world.CreateBody(b2body) );
}
//
function loop() {
if (getBrowserDimensions()) {
setWalls();
}
delta[0] += (0 - delta[0]) * .5;
delta[1] += (0 - delta[1]) * .5;
world.m_gravity.x = gravity.x * 350 + delta[0];
world.m_gravity.y = gravity.y * 350 + delta[1];
mouseDrag();
world.Step(timeStep, iterations);
for (i = 0; i < bodies.length; i++) {
var body = bodies[i];
var element = elements[i];
element.style.left = (body.m_position0.x - (element.width >> 1)) + 'px';
element.style.top = (body.m_position0.y - (element.height >> 1)) + 'px';
if (element.tagName == 'DIV') {
var style = 'rotate(' + (body.m_rotation0 * 57.2957795) + 'deg) translateZ(0)';
text.style.WebkitTransform = style;
text.style.MozTransform = style;
text.style.OTransform = style;
text.style.msTransform = style;
text.style.transform = style;
}
}
}
// .. BOX2D UTILS
function createBox(world, x, y, width, height, fixed) {
if (typeof(fixed) == 'undefined') {
fixed = true;
}
var boxSd = new b2BoxDef();
if (!fixed) {
boxSd.density = 1.0;
}
boxSd.extents.Set(width, height);
var boxBd = new b2BodyDef();
boxBd.AddShape(boxSd);
boxBd.position.Set(x,y);
return world.CreateBody(boxBd);
}
function createBox2(world, x, y, width, height, fixed) {
if (typeof(fixed) == 'undefined') {
fixed = true;
}
var boxSd = new b2CircleDef();
if (!fixed) {
boxSd.density = 1.0;
}
boxSd.radius = 100;
var boxBd = new b2BodyDef();
boxBd.AddShape(boxSd);
boxBd.position.Set(x,y);
return world.CreateBody(boxBd);
}
function mouseDrag()
{
// mouse press
if (createMode) {
createBall( mouse.x, mouse.y );
} else if (isMouseDown && !mouseJoint) {
var body = getBodyAtMouse();
if (body) {
var md = new b2MouseJointDef();
md.body1 = world.m_groundBody;
md.body2 = body;
md.target.Set(mouse.x, mouse.y);
md.maxForce = 30000 * body.m_mass;
// md.timeStep = timeStep;
mouseJoint = world.CreateJoint(md);
body.WakeUp();
} else {
// createMode = true;
}
}
// mouse release
if (!isMouseDown) {
createMode = false;
destroyMode = false;
if (mouseJoint) {
world.DestroyJoint(mouseJoint);
mouseJoint = null;
}
}
// mouse move
if (mouseJoint) {
var p2 = new b2Vec2(mouse.x, mouse.y);
mouseJoint.SetTarget(p2);
}
}
function getBodyAtMouse() {
// Make a small box.
var mousePVec = new b2Vec2();
mousePVec.Set(mouse.x, mouse.y);
var aabb = new b2AABB();
aabb.minVertex.Set(mouse.x - 1, mouse.y - 1);
aabb.maxVertex.Set(mouse.x + 1, mouse.y + 1);
// Query the world for overlapping shapes.
var k_maxCount = 10;
var shapes = new Array();
var count = world.Query(aabb, shapes, k_maxCount);
var body = null;
for (var i = 0; i < count; ++i) {
if (shapes[i].m_body.IsStatic() == false) {
if ( shapes[i].TestPoint(mousePVec) ) {
body = shapes[i].m_body;
break;
}
}
}
return body;
}
function setWalls() {
if (wallsSetted) {
world.DestroyBody(walls[0]);
world.DestroyBody(walls[1]);
world.DestroyBody(walls[2]);
world.DestroyBody(walls[3]);
walls[0] = null;
walls[1] = null;
walls[2] = null;
walls[3] = null;
}
walls[0] = createBox(world, stage[2] / 2, - wall_thickness, stage[2], wall_thickness);
// Bottom Wall Starts
walls[1] = createBox(world, stage[2], stage[3] + wall_thickness, stage[2], wall_thickness);
// Bottom Wall Ends
// function createBox(world, x, y, width, height, fixed) {
// Left Wall
walls[2] = createBox(world, - wall_thickness, stage[3] / 2, wall_thickness, stage[3]);
// Left Wall
// Right wall
walls[3] = createBox(world, stage[2] + wall_thickness, stage[3] / 2, wall_thickness, stage[3]);
// Right Wall
wallsSetted = true;
}
// BROWSER DIMENSIONS
function getBrowserDimensions() {
var changed = false;
if (stage[0] != window.screenX) {
delta[0] = (window.screenX - stage[0]) * 50;
stage[0] = window.screenX;
changed = true;
}
if (stage[1] != window.screenY) {
delta[1] = (window.screenY - stage[1]) * 50;
stage[1] = window.screenY;
changed = true;
}
if (stage[2] != window.innerWidth) {
stage[2] = window.innerWidth;
changed = true;
}
if (stage[3] != window.innerHeight) {
stage[3] = window.innerHeight;
changed = true;
}
return changed;
}
HTML
<div class="md:block hidden">
<img src="{{ asset('/assets/img/coin-1.png') }}" id="coin1" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-2.png') }}" id="coin2" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-3.png') }}" id="coin3" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-4.png') }}" id="coin4" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-5.png') }}" id="coin5" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-6.png') }}" id="coin6" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-7.png') }}" id="coin7" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-8.png') }}" id="coin8" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-9.png') }}" id="coin9" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-10.png') }}" id="coin10" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-11.png') }}" id="coin11" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-12.png') }}" id="coin12" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-13.png') }}" id="coin13" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-14.png') }}" id="coin14" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-15.png') }}" id="coin15" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-16.png') }}" id="coin16" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-17.png') }}" id="coin17" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-18.png') }}" id="coin18" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-19.png') }}" id="coin19" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-20.png') }}" id="coin20" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-21.png') }}" id="coin21" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-22.png') }}" id="coin22" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-23.png') }}" id="coin23" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-24.png') }}" id="coin24" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-25.png') }}" id="coin25" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-26.png') }}" id="coin26" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-27.png') }}" id="coin27" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-28.png') }}" id="coin28" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-29.png') }}" id="coin29" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-30.png') }}" id="coin30" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-31.png') }}" id="coin31" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-32.png') }}" id="coin32" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-33.png') }}" id="coin33" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-34.png') }}" id="coin34" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-35.png') }}" id="coin35" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-36.png') }}" id="coin36" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-37.png') }}" id="coin37" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-38.png') }}" id="coin38" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-39.png') }}" id="coin39" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-40.png') }}" id="coin40" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-41.png') }}" id="coin41" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-42.png') }}" id="coin42" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-43.png') }}" id="coin43" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-44.png') }}" id="coin44" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-45.png') }}" id="coin45" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-46.png') }}" id="coin46" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-47.png') }}" id="coin47" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-48.png') }}" id="coin48" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-49.png') }}" id="coin49" style="display: none;" width="32" height="32">
<img src="{{ asset('/assets/img/coin-50.png') }}" id="coin50" style="display: none;" width="32" height="32">
<div>
<div id="canvas"></div>
</div>
</div>
I have balls inside box, the box has 4 walls so ball won't go outside. It's draggable, droppable, pushable between each other. I want bottom wall a little curved so it may look like a ball in a bowl.

Box2D doesn't support concave shapes, only convex. So you need to approximate your curve with -either-
external triangles mapping over a quarter slice of a donut, the inner part of the donut being the internal wall
The corner being a shared point on all triangles and the other two points (inside) being calculated from the curve.
-And- then make them chained shapes to avoid sticking on the edges (ghost collisions).
https://box2d.org/posts/2020/06/ghost-collisions/
However, as the balls effectively are bound outside this curve anyway because of the box preventing ball perimeter from touching a corner, you could just draw the curve graphically without needing to include in box2d as the box2d check is redundant.Although this would prevent the balls rolling if they were dropped in gravity and fell down the side i.e. specifically for dragging or pulling this would be ok.

Related

javascript press key function

I want to add my javascript a key press function because my script run automaticaly
I want it when i press a specific key it will run and stop
The JS will not run / run automaticaly until i press "a"
When I press "a" it will run;
When I press "e" it will stop.
Can you add it to my javascript, Thanks.
here is the code bellow:
var currentpos = 0,
alt = 1,
curpos1 = 0,
curpos2 = -1
function initialize() {
startit()
}
function scrollwindow() {
if (document.all)
temp = document.body.scrollTop
else
temp = window.pageYOffset
if (alt == 0)
alt = 1
else
alt = 0
if (alt == 0)
curpos1 = temp
else
curpos2 = temp
if (curpos1 != curpos2) {
if (document.all)
currentpos = document.body.scrollTop + 1
else
currentpos = window.pageYOffset + 1
window.scroll(0, currentpos)
} else {
currentpos = 0
window.scroll(0, currentpos)
}
}
function startit() {
setInterval("scrollwindow()", 10) // change the value for speed the bigger the slow
}
window.onload = initialize
<header id="top"></header>
<main>
<article>
<!-- long form content here -->
</article>
<br>
<h1 id="chapter-heading">My Plug-in Spirit Ring</h1>
</br>
<div class=mp3>
<audio controls autoplay loop>
<source src="bg.mp3" type="audio/mpeg">
</audio>
</div>
<div style="font-size:0; position: absolute; left: 20%; top: 10%">
<img src="Cover.png" />
<img src="1.png" />
<img src="2.png" />
<img src="3.png" />
<img src="4.png" />
<img src="Thanks.gif" />
</div>
</main>
Thank you!
I would do this by creating a boolean value called "shouldScroll" and then using event listeners on your desired buttons to set the value of that variable. Then in your interval check to see if the boolean is true before calling your page scrolling function.
var currentpos = 0,
alt = 1,
curpos1 = 0,
curpos2 = -1
var shouldScroll = false;
document.addEventListener('keydown', (event) => {
if(event.key === 'a'){
event.preventDefault();
shouldScroll = true;
}
if(event.key === 'e'){
event.preventDefault();
shouldScroll = false;
}
});
function initialize() {
startit()
}
function scrollwindow() {
if (document.all)
temp = document.body.scrollTop
else
temp = window.pageYOffset
if (alt == 0)
alt = 1
else
alt = 0
if (alt == 0)
curpos1 = temp
else
curpos2 = temp
if (curpos1 != curpos2) {
if (document.all)
currentpos = document.body.scrollTop + 1
else
currentpos = window.pageYOffset + 1
window.scroll(0, currentpos)
} else {
currentpos = 0
window.scroll(0, currentpos)
}
}
function startit() {
setInterval(()=> shouldScroll && scrollwindow(), 10) // change the value for speed the bigger the slow
}
window.onload = initialize
main {
height: 4000px;
}
<header id="top"></header>
<main>
<article>
<!-- long form content here -->
</article>
<br>
<h1 id="chapter-heading">My Plug-in Spirit Ring</h1>
</br>
<div class=mp3>
<audio controls autoplay loop>
<source src="bg.mp3" type="audio/mpeg">
</audio>
</div>
<div style="font-size:0; position: absolute; left: 20%; top: 10%">
<img src="Cover.png" />
<img src="1.png" />
<img src="2.png" />
<img src="3.png" />
<img src="4.png" />
<img src="Thanks.gif" />
</div>
</main>
add in javascript file
document.addEventListener('keydown', function (e) {
console.log('key', e); // look at
if (e.code === 'KeyA') { // it is possible so
// todo
console.log('press a')
}
if (e.key === 'e') { // it is possible and so
// todo
}
console.log('press e')
})
you can do this using jquery.
$(document).bind('keyup', function(e){
if(e.which==65) {
// "a"
}
if(e.which==69) {
// "e"
}
});
for any word keyword code visit this article
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

TypeError: Cannot read property 'style' of undefined NodeJS

I got images with same width and height and onclick they should get bigger, so I made an function with an eventlistener for it but now it tells me that style isn't defined and I don't see the issue. I set the styles inside the img tag and also without style.
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />
js file
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', () => {
if (flag == true && window.innerWidth >= 769) {
paint[i].style.maxWidth = '95vw';
paint[i].style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
paint[i].style.maxWidth = '20%';
paint[i].style.minWidth = '300px';
paint[i].style.height = 'auto';
flag = true;
}
})
}
If I try to use getelementById everything works fine but I don't want for every image an eventlistener.
Use event.target in the eventlistener function to find the clicked image.
const paint = document.getElementsByClassName('painting');
let flag = true;
for (var i = 0; i < paint.length; i++) {
paint[i].style.maxWidth = '20%';
paint[i].style.height = '250px';
paint[i].style.minWidth = '300px';
paint[i].addEventListener('click', (event) => {
console.log(event.target)
if (flag == true && window.innerWidth >= 769) {
event.target.style.maxWidth = '95vw';
event.target.style.height = 'auto';
flag = false;
} else if (flag == true && window.innerWidth < 769) {
} else {
event.target.style.maxWidth = '20%';
event.target.style.minWidth = '300px';
event.target.style.height = 'auto';
flag = true;
}
})
}
<img class="painting" src="<%= post.paintingsP %>" />
<img class="painting" style="max-width: 20%; min-width: 300px; height: 250px;"src="<%= post.paintingsP2 %>" />

Why is my sprite speeding up without changing variables?

I have a bug in this code somewhere that cause the ship to fly faster and faster in space after returning from the planet. I cant figure this one out.
I set the speed to 0.1 so that its super slow in space. When you click on the planet, i run a function that will move canvas's off screen and use zindex to brong a div tag to the top of the stack. When you land and return to orbit, the ship will move slightly faster. After doing it about 10-15 times the ship moves far greater than the 0.1 speed that is set. I will include the html, js and css so you can run it to test.
Here is the whole code.
// Canvas Context's
var canvasMS = document.getElementById('MainScreen_cvs');
var ctxMain = canvasMS.getContext('2d');
var canvasShip = document.getElementById('Ship_cvs');
var ctxShip = canvasShip.getContext('2d');
var PlanetDiv = document.getElementById('PlanetDiv');
var OrbitReturn = document.getElementById('OrbitReturn');
var canvasPlanets = document.getElementById('Planets_cvs');
var ctxPlanets = canvasPlanets.getContext('2d');
var canvasHUD = document.getElementById('HUD_cvs');
var ctxHUD = canvasHUD.getContext('2d');
var canvasSurface = document.getElementById('Surface_cvs');
var ctxSurface = canvasSurface.getContext('2d');
// ----------------------------------End Canvas Context
var Player1;
var Planet1;
var planetClicked;
var gameWidth = canvasMS.width;
var gameHeight = canvasMS.height;
var mouseX = 10000;
var mouseY = 10000;
var SpaceMapX = 10;
var SpaceMapY = 10;
var SurfaceMap = 0;
var SurfaceMap2 = -1600;
var inSpace = true;
var onSurface = false;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
// Load Images
var imgMap = new Image();
imgMap.src = 'images/bg1.png';
var imgButtons = new Image();
imgButtons.src = 'images/button_sprite.png';
var imgBlueWindow = new Image();
imgBlueWindow.src = 'images/blue_window.png';
var imgSprite = new Image();
imgSprite.src = 'images/sprite.png';
var imgPlanets = new Image();
imgPlanets.src = 'images/earthlike_p1.png';
var imgBluesky1 = new Image();
imgBluesky1.src = 'images/bluesky1.png';
var imgBluesky2 = new Image();
imgBluesky2.src = 'images/bluesky2.png';
imgMap.addEventListener('load',init,false);
// ------------- End Loading Images
//-------------------- Create Game Objects ----------------
function CreateGameObjects(){
Player1 = new Ship();
Planet1 = new Planet();
};
//---------------END CREATING GAME OBJECTS------------------
function init(){ //----------------------------------------------- GAME INITIALIZATION
document.addEventListener('keydown',checkKeyDown,false);
document.addEventListener('keyup',checkKeyUp,false);
document.addEventListener("mousedown", checkMouseDown, false);
document.addEventListener("mouseup", checkMouseUp, false);
CreateGameObjects();
Loop();
};
function Loop() { // ---------------- Main Game Loop
clearCtx();
DrawGameObjects();
requestAnimFrame(Loop);
};
function planetSurface(){
if(onSurface){
clearCtx();
HUD();
Player1.draw();
if(mouseY < 21 && mouseX > 693){
ReturntoOrbit();
}
planetClicked.drawSurfaceImg();
var CloseButton = '<button style="float:right;" type="button">Return to Orbit</button>' ;
OrbitReturn.innerHTML = CloseButton;
requestAnimFrame(planetSurface);
}
};
function DrawGameObjects(){
Player1.draw();
Planet1.draw();
HUD();
};
function HUD(){
canvasHUD.style.zIndex = "100";
if (onSurface){
ctxHUD.fillStyle = "#000";
ctxHUD.fillText("locSurface: " + planetClicked.locSurface, 20,30);
}
if (inSpace)
ctxHUD.fillStyle = "#fff";
ctxHUD.fillText("Speed: " + Player1.speed, 60,60);
ctxHUD.fillText("drawX: " + Player1.drawX, 600,40);
ctxHUD.fillText("drawY: " + Player1.drawY, 600,30);
// ctxHUD.fillText("Planet Clicked: " + Planet1.isClicked, 600,50);
}
//----------------------------------------------------------- Objects
/************************************************************************************/
//--------------------------------- SPACE SHIP --------------------------------------
function Ship(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 60;
this.srcH = 60;
this.drawX = 20 ;
this.drawY = 50 ;
this.speed = 0;
this.surfaceSpeed = 10;
this.drift = 0.45;
this.w = 16;
this.h = 16;
this.isUpKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.isRightKey = false;
this.isSpacebar = false;
this.direction = "n/a";
this.isMoving = false;
this.isClicked = false;
this.surfX = 350;
this.surfY = 200;
};
Ship.prototype.draw = function() {
if(inSpace)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
if(onSurface)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.surfX,this.surfY,this.w,this.h);
this.checkPos(planetClicked);
};
Ship.prototype.checkPos = function (PlanetX){
if(inSpace){
this.srcY = 0;
this.srcW = 60;
this.w = 16;
this.h = 16;
this.speed = 0.1;
//----------------------------- Move Ship and Map based on the speed of the ship.
if(this.isLeftKey){
this.drawX -= this.speed;
if(SpaceMapX >= 1){
SpaceMapX -= this.speed;
}
}
if(this.isRightKey){
this.drawX += this.speed;
if(SpaceMapX <= 2190)SpaceMapX += this.speed;
}
if(this.isDownKey){
this.drawY += this.speed;
if(SpaceMapY <= 2490)SpaceMapY += this.speed;
}
if (this.isUpKey) {
this.drawY -= this.speed;
if(SpaceMapY >= 1){
SpaceMapY -= this.speed;
}
}
if (SpaceMapY < 0) {SpaceMapY = 0;}
if (SpaceMapX < 0 ) {SpaceMapX = 0}
//--------------------------------------------------------------------END
//-----------------------------------Change Ship Graphic based on direction and map boundaries.
if(this.isUpKey) this.srcX = 360;
if(this.isDownKey) this.srcX = 120;
if(this.isLeftKey) this.srcX = 240;
if(this.isRightKey) this.srcX = 0;
if(this.isUpKey && this.isLeftKey) this.srcX = 300;
if(this.isUpKey && this.isRightKey) this.srcX = 420;
if(this.isDownKey && this.isLeftKey) this.srcX = 180;
if(this.isDownKey && this.isRightKey) this.srcX = 60;
if (this.drawX <= 5) this.drawX = 5;
if (this.drawY <= 5) {this.drawY = 5};
if (this.drawY >= 480) {this.drawY = 480};
if (this.drawX >= 780) {this.drawX = 780};
//----------------------------------------------------------------END
ctxMain.drawImage(imgMap,SpaceMapX,SpaceMapY,gameWidth,gameHeight,0,0,gameWidth,gameHeight);
}
if (onSurface) {
this.srcY = 240;
this.srcW = 92;
this.w = 93;
this.h = 60;
if(this.isLeftKey){
PlanetX.locSurface -= this.surfaceSpeed;
SurfaceMap += this.surfaceSpeed;
SurfaceMap2 += this.surfaceSpeed;
PlanetX.MapDirection = -1;
this.srcX = 93;
}
if(this.isRightKey){
PlanetX.locSurface += this.surfaceSpeed;
SurfaceMap -= this.surfaceSpeed;
SurfaceMap2 -= this.surfaceSpeed;
PlanetX.MapDirection = 1;
this.srcX = 0;
}
}
};
//------------------------------END OF SPACE SHIP ------------------------------------
//----------------------------- PLANET OBJECT INFO ------------------------------------
function Planet(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 100;
this.srcH = 100;
this.w = 50;
this.h = 50;
this.coordX = 100;
this.coordY = 100;
this.planetType = "Small Earthlike Planet."
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
this.surfaceIMG = imgBluesky1;
this.isClicked = false;
this.locSurface = 0;
};
Planet.prototype.draw = function(){
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
ifClicked(this);
if(this.isClicked){
PlanetDiv.style.display = "block";
var LandPlanetDivButton = '<button id="LandPlanetDivButton" type="button" onclick="landOnSurface();">Land On Surface</button>';
var ClosePlanetDivButton = '<button id="ClosePlanetDivButton" type="button" onclick="ClosePlanetDiv();">Close (x)</button><br/><p id="PlanetDivText">' ;
PlanetDiv.style.zIndex = "2";
HideCanvas();
planetClicked = this;
PlanetDiv.innerHTML = LandPlanetDivButton + ClosePlanetDivButton + this.planetType; + '</p>';
}
ctxPlanets.drawImage(imgPlanets,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
};
Planet.prototype.drawSurfaceImg = function(){
if(SurfaceMap2 >= 0) SurfaceMap2 = -1600;
if(SurfaceMap2 < -1600) SurfaceMap2 = -1;
if(SurfaceMap >= 1600) SurfaceMap = 0;
if(SurfaceMap < 0) SurfaceMap = 1599;
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap, 0, 1600, gameHeight);
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap2, 0, 1600, gameHeight);
};
//----------------------------- END OF PLANET OBJECT -----------------------------------
//-----end Objects
function randomFromTo(from,to){
return Math.floor(Math.random()*(to-from+1)+from);
};
function closestNum(Num, a){
var num = Num + (gameWidth/2);
var closest = a[0];
var difference = Math.abs (num - closest);
for (var i = 0; i < a.length; i++) {
var difference2 = Math.abs (num - a[i]);
if (difference2 < difference) {
difference = difference2;
closest = a[i];
}
}
return closest;
};
function sortNum(a)
{
var swapped;
do{
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
}while (swapped);
};
function ifClicked(obj){
if(mouseX >= obj.drawX && mouseX <= obj.drawX + obj.w){
if(mouseY >= obj.drawY && mouseY <= obj.drawY + obj.h){
obj.isClicked = true;
}
}
else{
obj.isClicked = false;
}
};
function clearCtx() {
ctxMain.clearRect(0,0,gameWidth,gameHeight);
ctxShip.clearRect(0,0,gameWidth,gameHeight);
ctxPlanets.clearRect(0,0,gameWidth,gameHeight);
ctxHUD.clearRect(0,0,gameWidth,gameHeight);
ctxSurface.clearRect(0,0,gameWidth,gameHeight);
};
function checkKeyDown(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = true;
Player1.direction = "North";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = true;
Player1.direction = "East"
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = true;
Player1.direction = "South";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = true;
Player1.direction = "West";
Player1.isMoving = true;
e.preventDefault();
}
};
function checkKeyUp(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = false;
Player1.isMoving = false;
e.preventDefault();
}
};
function clearMouse(){
mouseX = 10000;
mouseY = 10000;
};
function checkMouseDown(e) {
var mX = (e.clientX - (canvasMS.offsetLeft - canvasMS.scrollLeft));
var mY = (e.clientY - (canvasMS.offsetTop - canvasMS.scrollTop));
if(mX <= gameWidth && mX >= 0) mouseX = mX;
if(mY <= gameHeight && mY >= 0) mouseY = mY;
//mouseIsDown = true;
};
function checkMouseUp(e){
//mouseIsDown = false;
clearMouse();
};
function ClosePlanetDiv (){
PlanetDiv.style.zIndex = "-2";
PlanetDiv.innerHTML = "";
PlanetDiv.style.display = "none";
ShowCanvas();
};
function HideCanvas(){
canvasShip.style.marginTop = "-10000px";
canvasPlanets.style.marginTop = "-10000px";
};
function ShowCanvas(){
canvasShip.style.marginTop = "-500px";
canvasPlanets.style.marginTop = "-500px";
};
function landOnSurface(){
ClosePlanetDiv();
inSpace = false;
onSurface = true;
Player1.srcX = 0;
planetSurface();
canvasSurface.style.display = "block";
OrbitReturn.style.display = "block";
};
function ReturntoOrbit(){
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
Loop();
};
<!doctype html>
<html lang='en'>
<head>
<meta charset="utf-8">
<title>Space Explorer</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Functions.js"></script>
</head>
<body>
<canvas id="MainScreen_cvs" width="800" height="500"></canvas>
<div id="PlanetDiv"></div>
<canvas id="Surface_cvs" width="800" height="500"></canvas>
<canvas id="Ship_cvs" width="800" height="500"></canvas>
<canvas id="Planets_cvs" width="800" height="500"></canvas>
<canvas id="HUD_cvs" width="800" height="500"></canvas>
<div id="OrbitReturn"></div>
<div id="log">
<h1 style="color:blue;">Recent updates will be logged here when made live.</h1>
<hr />
<h3> Wednesday August 3, 2016 </h3>
<ul>
<li> HTML file completed. Working on getting JS files started.</li>
<li> JS files created. </li>
<li>Basic ship & flight functions in place. Basic star map initialized.</li>
</ul>
<hr />
</div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>
body {
background: #303030;
}
#MainScreen_cvs {
position: relative;
display: block;
background: #777777 ;
margin: 30px auto 0px;
z-index: 1;
}
#Surface_cvs{
position: relative;
display: none;
z-index: 1;
margin: -500px auto 0px;
}
#Ship_cvs, #Planets_cvs, #HUD_cvs {
display: block;
position: relative;
margin: -500px auto 0px;
z-index: 1;
}
#log {
display: block;
position: absolute;
top: 560px;
left: 233px;
background: #ffffff;
overflow: scroll;
width: 800px;
height: 300px;
z-index: 3;
}
#OrbitReturn{
display: block;
position: relative;
width: 800px;
height: 500px;
z-index: 3;
margin: -500px auto 0px;
}
#PlanetDiv {
display: block;
position: relative;
width: 800px;
height: 500px;
background-image: url("images/Sky.jpg");
z-index: -2;
margin: -500px auto 0px;
}
#ClosePlanetDivButton{
float: right;
}
#LandPlanetDivButton{
position: absolute;
top: 400px;
left: 325px;
font-size: 20px;
}
#PlanetDivText{
text-indent: 50px;
font-size: 20px;
}
Something is happening with Ship.prototype.checkPos. Each time you land on the planet, it looks like the checking pauses, then starts up when you enter orbit. But this time he checkPos is getting called faster.
I could keep staring at it but you might be able to figure it out from there. I put a console.log('checkPos') at the top of that function and watched it pause and restart.
Ship.prototype.checkPos = function(PlanetX) {
console.log('checkPos');
if (inSpace) {
...
I think it might be here
function ReturntoOrbit() {
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
//Loop(); <--- this little guy. Get rid of him.
};

jQuery slider with buttons is buggy

This the html:
<div id = "slideshow">
<div id="slideshowWindow">
<div class="slide"><img src="slideshow.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8185.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8211.jpg" alt="" /></div>
<div class="slide"><img src="OrganicSoilad.jpg" alt="" /></div>
<div class="slide"><img src="DSC_8243.jpg" alt="" /></div>
<input style = "display: none;" value = "" id="hide"/>
</div>
Everything seems to work fine except for the prev() button. It just bugs out if you click it more than once. It gets all buggy. I'm relatively new to jquery and if anyone has any insight on how to stop the slider from sliding while on hover that would also be helpful.
the javascript:
$(document).ready(function() {
$(".content").mouseenter(function(){
$( ".arrows" ).fadeIn(100);
});
$('.content').mouseleave(function(){
$( ".arrows" ).fadeOut(700);
});
var currentPosition = 0;
var $hide = $('#hide');
$hide.val(currentPosition);
var slideWidth = 1140;
var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval;
var speed = 5000; slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>');
slides.css({ 'float' : 'left' });
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
function changePosition() {
currentPosition = $('#hide').val();
if(currentPosition == numberOfSlides - 1)
{
currentPosition = 0; $hide.val(currentPosition);
} else {
currentPosition++; $hide.val(currentPosition);
}
moveSlide();
}
function moveSlide() {
$current = $('#slidesHolder').css('padding-left');
$current_num = $current.replace('px' , '');
$padding = $current_num;
$('#slidesHolder').animate({'paddingLeft': $padding});
/* alert($padding); */
/*alert($('#slidesHolder').css('padding-left')); */
$('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)});
$('#media').html(currentPosition);
}
});
function next()
{
currentPosition = $('#hide').val();
slideWidth = 1140;
++currentPosition; if(currentPosition > 4){currentPosition =0;}
$('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)});
$('#hide').val(currentPosition)
$('#media').html(currentPosition);
}
function prev()
{
currentPosition = $('#hide').val();
slideWidth = 1140;
$left = 1140;
if(currentPosition == 0)
{
currentPosition = 5;
}
else
{
if($('#slidesHolder').css('padding-left') == '1140px')
{
$left = $left + $left;
}
$('#hide').val(currentPosition);
$('#slidesHolder').animate({'paddingLeft' : $left});
if(currentPosition == 0)
{
currentPosition = 4;
}
else{
--currentPosition;
}
$('#hide').val(currentPosition);
$('#media').html(currentPosition);
}
}

How do I get my arrow widget to rotate back to start on second click

After following two YouTube lessons, I now have a nice arrow widget that fades in, rotates to 180 degrees and fades out controlled from one button. I do not know how to make the arrow rotate back to 0 on the second click of this button.
Probably not the most elegant of code, but here we are:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fade In and Out</title>
<style type="text/css">
div.contentbox {
width: 50px;
height: 50px;
padding: 20px;
opacity: 0;
}
</style>
<script type="text/javascript">
var fade_in_from = 0;
var fade_out_from = 10;
function fadeIn(element) {
var target = document.getElementById(element)
target.style.display = "block";
var newSetting = fade_in_from / 10;
target.style.opacity = newSetting;
fade_in_from++;
if(fade_in_from == 10) {
target.style.opacity = 1;
clearTimeout(loopTimer);
fade_in_from = 0;
return false;
}
var loopTimer = setTimeout('fadeIn(\''+element+'\')', 50);
}
function fadeOut(element) {
var target = document.getElementById(element)
var newSetting = fade_out_from / 10;
target.style.opacity = newSetting;
fade_out_from--;
if(fade_out_from == 0) {
target.style.opacity = 0;
clearTimeout(loopTimer);
fade_out_from = 10;
return false;
}
var loopTimer = setTimeout('fadeOut(\''+element+'\')', 50);
}
var looper;
var degrees = 0;
function rotateAnimation(el,speed)
{
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
} else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout ('rotateAnimation(\''+el+'\','+speed+')',speed);
degrees++;
if(degrees > 179){
clearTimeout(looper)
}
}
</script>
</head>
<body>
<button onmouseover="fadeIn('arrow_box')": onmouseout="fadeOut('arrow_box')": onclick="rotateAnimation('arrow',5)">fade in/out</button>
<div id="arrow_box" class="contentbox"><img id="arrow" img src="images/Arrow.png" width="50" height="50" alt="Arrow" /></div>
</body>
</html>
Please help.
Create a new variable to remember the direction and then increment or decrement the degrees depending on which direction you want to go.
Here is a JSfiddle link of a working solution.
var looper;
var degrees = 0;
var direction = 0;
function rotateAnimation(el,speed){
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
}else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout
('rotateAnimation(\''+el+'\','+speed+')',speed);
if(direction === 0){
degrees++;
if(degrees > 179){
direction = 1;
clearTimeout(looper);
}
}else {
degrees--;
if(degrees < 1){
direction = 0;
clearTimeout(looper);
}
}
}

Categories

Resources