Canvas - How to do background image moving - javascript

I want background image to keep moving from left to right.
Any idea how can I do that ? I tried to use code from stackoverflow, didnt work, I tried to google, didnt work.
This is my code. There is nothing about the moving background I am just placing it here because it might help. I´d like to know why any code never worked.
<!DOCTYPE html>
<html dir='ltr'>
<head>
<title>Temponary Rush</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script type='text/javascript' src='js/classes.js'></script>
<style>
body {
background-color: #232B2B;
background-image:url('../web/css/cave-background.png');
background-position:top;
background-repeat:no-repeat;
color:#FFFFFF;
}
#container{
flex-flow: row nowrap;
display: -webkit-flex;
-webkit-justify-content: space-around;
display: flex;
justify-content: space-around;
}
#container > div {
background: #5F85DB;
padding: 5px;
color: #fff;
font-weight: bold;
font-family: Tahoma;
border:5px inset #DC3D24;
background-color:#232B2B;
}
#container > .advert {
width:200px;
}
canvas {
background-image:url('imgs/backgrounds/cave-bcg.png');
background-position:center;
}
</style>
</head>
<body>
<div id='container'>
<div id='left' class='advert'>
levá strana
</div>
<div id='center'>
<canvas id="ctx" width="800" height="600"></canvas>
<script type='text/javascript'>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
ctx.fillStyle = 'white';
var player = {
x: 10,
y: 549,
spdX: 1,
spdY: 51,
width:50,
height:50
};
var obstacles = [
];
var allowedJump = true;
document.onkeydown = function(event){
if (event.keyCode === 32 && allowedJump) {
for(i; i<10;i++){
setTimeout(function(){
player.y-= player.spdY/10;
},60);
}
setTimeout(function(){
allowedJump = true;
player.y+=player.spdY;
},600);
};
allowedJump = false;
};
setInterval(update,10);
function update(){
ctx.clearRect(0,0,800,600,45);
ctx.fillRect(player.x, player.y, player.width, player.height);
player.x += player.spdX;
for(i = 0; i < obstacles.length; i++) {
ctx.fillRect(obstacles[i][0], obstacles[i][1], obstacles[i][2], obstacles[i][3]);
var is_colliding = collision.testCollision(player,obstacles[i][0], obstacles[i][1],obstacles[i][2],obstacles[i][3]);
if(is_colliding) {
afterImpact.stun(2,player);
}
}
}
</script>
</div>
<div id='right' class='advert'>
pravá strana
</div>
</div>
</body>
</html>
I have the website on xampp server for now, later I will go to node.js server.
this is my file tree.

please remove this code from body
body {
background-color: #232B2B;
background-image:url('../web/css/cave-background.png');
background-position:top;
background-repeat:no-repeat;
color:#FFFFFF;
}
you can set the following div code inside the body tag
div{
background-color: #232B2B;
background-image:url('../web/css/cave-background.png');
background-position:top;
background-repeat:no-repeat;
}

Related

how can I let 3 div elements being resizable

what I want to see the result is 2 set of split view screen (or more), one is vertical, one is horizontal, but in the same javascript file. If it's possible to do in a single JavaScript file will be good
I tried to use this one to make it but it seems like not how to make that.
Here's the code I'm trying to make two div elements and its vertical
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my app</title>
<style>
.container {
width: 202px;
height: 406px;
border: 1px solid black;
display: flex;
flex-direction: column;
}
.top {
width: 200px;
height: 200px;
border: 1px solid red;
min-height: 100px;
}
.resizer {
width: 202px;
height: 2px;
background-color: green;
}
.resizer:hover {
cursor: ns-resize;
}
.bottom {
width: 200px;
height: 200px;
border: 1px solid blue;
flex: 1 1 0%;
min-height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="top" id="top">
something here
</div>
<div class="resizer" id="resizer"></div>
<div class="bottom" id="bottom">
something too
</div>
</div>
<script>
const resizer = document.getElementById('resizer');
const topSection = document.getElementById('top');
const bottomSection = document.getElementById('bottom');
let x = 0;
let y = 0;
let topSectionHeight = 0;
const mouseDownHandler = function (e) {
x = e.clientX;
y = e.clientY;
topSectionHeight = topSection.getBoundingClientRect().height;
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
}
resizer.addEventListener('mousedown', mouseDownHandler);
const mouseMoveHandler = function (e) {
const dx = e.clientX - x;
const dy = e.clientY - y;
const newtopSectionHeight = ((topSectionHeight + dy) * 100) / resizer.parentNode.getBoundingClientRect().height;
topSection.style.height = `${newtopSectionHeight}%`;
resizer.style.cursor = 'ns-resize';
document.body.style.cursor = 'ns-resize';
topSection.style.userSelect = 'none';
topSection.style.pointerEvents = 'none';
bottomSection.style.userSelect = 'none';
bottomSection.style.pointerEvents = 'none';
}
const mouseUpHandler = function () {
resizer.style.removeProperty('cursor');
document.body.style.removeProperty('cursor');
actionBasic.style.removeProperty('user-select');
actionBasic.style.removeProperty('pointer-events');
bottomSection.style.removeProperty('user-select');
bottomSection.style.removeProperty('pointer-events');
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
}
</script>
</body>
</html>
thank you for reading so far, please help me if you're able to! If any information is needed, please tell me below and I'll provide it as soon as possible.

Track position of other element

I have an inner circle which tracks the position of my pointer, Now I want the circle color to change when it hovers on the h2 tag.
can anyone help??
I have tried searching few places but all were on "mouseover".
note: only when the inner-circle hovers on h2 not the mouse pointer, the inner circle's color should change.
<!doctype>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Roll Over Eyes</title>
<style>
body
{
display: flex;
align-items: center;
justify-content: center;
height: 900px;
border: 1px solid black;
}
.main-circle
{
display: flex;
align-items: center;
justify-content: center;
position: relative;
height: 350px;
width: 350px;
border: 1px solid black;
border-radius: 10%;
}
#inner-circle
{
position: absolute;
height: 50px;
width: 50px;
border: 1px solid black;
border-radius: 50%;
background: #af4b23;
}
.message
{
display:none;
width: 75%;
}
</style>
</head>
<body>
<div class="main-circle">
<div id="inner-circle">
</div>
<h2 class="message">Your Outside the box</h2>
<h2 class="message">Your inside the box, now move the mouse to move the circle.</h2>
</div>
<script>
(function()
{
var ele= document.getElementById("inner-circle");
var hea= document.getElementsByClassName("message");
var body=document.body;
var height=body.clientHeight;
var width=body.clientWidth;
var move = function(event)
{
var x= event.clientX;
var y= event.clientY;
ele.style.left = ( x/width )*300;
ele.style.top = ( y/height )*300;
}
var display = function()
{
console.log("done");
hea[0].style.display="inline-block";
hea[1].style.display="none";
}
var hide = function()
{
console.log("done hiden");
hea[0].style.display="none";
hea[1].style.display="inline-block";
}
var effect = function()
{
ele.style.backgroundColor= "rgba(0,0,0,0.5)";
}
var deflt = function()
{
ele.style.backgroundColor= "#af4b23";
}
body.addEventListener("mousemove",function(){ move(event) },false);
body.addEventListener("mouseout",display,false);
body.addEventListener("mouseover",hide,false);
hea[1].addEventListener("mouseover",effect,false);
hea[1].addEventListener("mouseout",deflt,false);
})();
</script>
</body>
</html>
You can try this:
(function()
{
var ele= document.getElementById("inner-circle");
var hea= document.getElementsByClassName("message");
var body=document.body;
var height=body.clientHeight;
var width=body.clientWidth;
var move = function(event)
{
var x= event.clientX;
var y= event.clientY;
ele.style.left = ( x/width )*300;
ele.style.top = ( y/height )*300;
var e_pos = ele.getBoundingClientRect();
var h_pos = hea[1].getBoundingClientRect();
if(e_pos.bottom>=h_pos.top && e_pos.top<=h_pos.bottom && e_pos.right>=h_pos.left && e_pos.left<=h_pos.right){
ele.style.backgroundColor= "rgba(0,0,0,0.5)";
}else{
ele.style.backgroundColor= "#af4b23";
};
}
var display = function()
{
//console.log("done");
hea[0].style.display="inline-block";
hea[1].style.display="none";
}
var hide = function()
{
//console.log("done hiden");
hea[0].style.display="none";
hea[1].style.display="inline-block";
}
body.addEventListener("mousemove",function(){ move(event) },false);
body.addEventListener("mouseout",display,false);
body.addEventListener("mouseover",hide,false);
})();
in this answer i set background-color after setting left and top of ele. also i have removed two last eventListeners.
Look at the result online and change it yorself!
the border is added to detect h2's bounds.

It has the different layouts between when I press [enter] and click [refresh]

When I practice waterfall flow layout, it has a problemlike this:
When the page is first loaded or I click [refresh] or press [F5], it looks bad. Each column of the images stacks!
But when I press [enter] in address bar or scroll with mouse, it looks good.
So how can I solve the problem? Thanks a lot!
var dataPic=["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg"];
var curtIndex=0;
$(document).ready(function(){
$(window).on("load",function(){
init(); //initializes the display with 30 pictures,call loadPic()
placePic(); //layout
});
$(window).scroll(function(){
while(scrollSlide()){ //whether it needs loading more pictures
loadPic(); //div and img can be loaded dynamically
}
placePic(); //layout for the elements that are just loaded
});
});
function init(){
var i=30;
do{
loadPic();
}while(i-- >= 0);
placePic();
}
function initSlide(){
var box=$(".box");
var lastboxHeight=box.last().get(0).offsetTop;
var documentHeight=$(document).height();
return (lastboxHeight<documentHeight)?true:false;
}
function currentIndex(){
if(curtIndex==9){
curtIndex=0;
}
return curtIndex;
}
function loadPic(){
var boxadd=$("<div>").addClass("box").appendTo($("#container"));
var current=$("<div>").addClass("pic").appendTo(boxadd);
$("<img>").attr("src","./img/"+dataPic[currentIndex()]).appendTo(current);
curtIndex++;
}
function placePic(){
var box=$(".box");
var boxWidth=box.eq(0).width();
var num=Math.floor($(window).width()/boxWidth);
var boxArr=[];
box.each(function(index,value){
var boxHeight=box.eq(index).outerHeight(true);
if(index<num){
boxArr[index]=boxHeight;
}
else{
var minboxHeight=Math.min.apply(null,boxArr);
var minboxIndex=$.inArray(minboxHeight,boxArr);
$(value).css({
"margin":"10px",
"box-shadow":"2px 2px 2px rgba(0,0,0,.3)",
"border-radius": "4px",
"position":"absolute",
"top":minboxHeight,
"left":box.eq(minboxIndex).position().left
});
boxArr[minboxIndex]+=box.eq(index).outerHeight(true);
}
});
}
function scrollSlide(){
var box=$(".box");
var lastboxHeight=box.last().get(0).offsetTop+Math.floor(box.last().height()/2);
var documentHeight=$(window).height();
var scrollHeight=$(window).scrollTop();
return (lastboxHeight<documentHeight+scrollHeight)?true:false;
}
*{
margin: 0px;
padding: 0px;
}
#container{
margin-left: auto;
margin-right: auto;
}
.box{
margin:10px;
box-shadow:2px 2px 2px rgba(0,0,0,.3);
border-radius: 4px;
position: relative;
float: left;
}
.pic img{
margin: 0px;
padding: 0px;
width:200px;
height: auto;
vertical-align: bottom;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="mystyle.css">
</head>
<body bgcolor="">
<div id="container">
</div>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script src="testjs.js"></script>
</body>
</html>

JavaScript is Not Working in any of my Browsers

I am just learning JavaScript and for some reason this simple (Example 1 from Chapter One) example is not working (Jon Duckett's JavaScript and Jquery book) in any of my browsers: FireFox, IE, and Chrome. I made sure JavaScript is turned on. I also put noscript tags in my index.html file to make sure I had JavaScript on. My jsFiddle works perfectly, but nothing in my browsers. Here is my jsFiddle with everything I have in my Atom editor. My links are correct because I copied the full path and then pasted it into the src. I then deleted all the C:\users....... until I got into the folder with all of the files to end up with what is in the jsFiddle.
html:
<!doctype html>
<html lang="en">
<head>
<meta charset="etf-8" />
<title>Greeting JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
<script src="scripts/greeting.js"></script>
</head>
<body>
<noscript>Your Browser Does Not Support JavaScript. Please Enable It.</noscript>
<section>
<div id="header">
<h1>Constructive & Co.</h1>
</div>
<h3 id="greeting"></h3>
<p>For all orders and inquiries please call <em>555-3344</em></p>
</section>
</body>
</html>
javascript:
var today = new Date();
var hourNow = today.getHours();
var greeting;
if (hourNow > 18) {
greeting = 'Good evening!';
} else if (hourNow > 12) {
greeting = 'Good afternoon!';
} else if (hourNow > 0) {
greeting = 'Good morning!';
} else {
greeting = 'Welcome!';
}
document.getElementById("greeting").innerHTML = greeting;
css:
#import url(http://fonts.googleapis.com/css?family=Open+Sans:800italic);
body {
font-family: "Courier New", Courier, monospace;
/*background: url("../images/constructive-backdrop.jpg") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;*/
background: #a18957;
margin: 0px;
padding: 0px;
text-align: center;
}
section {
margin-top: 20px;
margin-left: 20px;
height: 500px;
width: 400px;
background: #eee;
border: 1px solid #292929;
}
#header {
height: 200px;
margin: 10px;
background: rgba(227, 192, 186, 0.78);
}
h1 {
margin: 0px;
position: relative;
top: 45%;
}
h3 {
height: 100px;
margin: 10px;
background: red;
}
p {
margin: 10px;
height: 100px;
}
Thank You
You want to add the script tag at the end of your html. The element greeting doesn't exist, when you are executing it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Greeting JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<noscript>Your Browser Does Not Support JavaScript. Please Enable It.</noscript>
<section>
<div id="header">
<h1>Constructive & Co.</h1>
</div>
<h3 id="greeting"></h3>
<p>For all orders and inquiries please call <em>555-3344</em></p>
</section>
<script src="scripts/greeting.js"></script>
</body>
</html>
Or you leave it in the head and wrap the script into
addEventListener("readystatechange", function () {
if (document.readyState === "interactive") {
var today = new Date();
var hourNow = today.getHours();
var greeting;
if (hourNow > 18) {
greeting = 'Good evening!';
} else if (hourNow > 12) {
greeting = 'Good afternoon!';
} else if (hourNow > 0) {
greeting = 'Good morning!';
} else {
greeting = 'Welcome!';
}
document.getElementById("greeting").innerHTML = greeting;
}
}, false);
It is wonderful you use document.getElementById, instead of document.write!

Animated image (e.g. non-GIF) with JavaScript and CSS?

I had been trying to animate a .png file with JavaScript while following this method. This is the .png file that I want to animate. I want the animated logo to be right by "Cupquake," but the logo doesn't even show up, let alone animate. However, changing "span class=logoCquake" in HTML to a div class displays the logo, but it is below the text.
My JavaScript file:
var scrollUp = (function () {
var timerId;
return function (height, times, element) {
var i = 0;
timerId = setInterval(function () {
if (i > times)
i = 0;
element.style.backgroundPosition = "0px -" + i * height + 'px';
i++;
}, 100);
};
})();
scrollUp(130, 30, document.getElementByClass('logoCquake'))
My HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script src="../scripts/logoCquake.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<br>
<br>
<br>
<span class="ninja">Ninja</span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
CSS file:
#font-face
{
font-family: typo_semib;
src: url('fonts/typo_semib.ttf');
}
#font-face
{
font-family: typo_light;
src: url('fonts/typo_light.ttf');
}
.wrapper .header
{
height: 250px;
width: 100%;
background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#ffa200), color-stop(100%,#d25400));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa200',endColorstr='#d25400',GradientType=0);
background: -moz-linear-gradient(top,#ffa200,#d25400);
background-image: -o-linear-gradient(#ffa200,#d25400);
overflow: hidden;
}
.wrapper .header .topbar
{
height: 60px;
background-image: url(../imgz/head/hBarSBg.png);
background-repeat: repeat-x;
}
.wrapper .header .topbar .mCquake
{
height: 37px;
width: 278px;
background-image: url(../imgz/head/mCqRight.png);
background-repeat: no-repeat;
float: none;
float: right !important;
margin-right: 10px;
margin-top: 11.5px;
margin-bottom: 11.5px;
}
.wrapper .header .ninja
{
font-family: typo_semib;
font-size: 48px;
color: #303030;
margin-left: 55px;
}
.wrapper .header .cupquake
{
font-family: typo_light;
font-size: 48px;
color: #303030;
}
.wrapper .header .logoCquake
{
height: 112px;
width: 130px;
background-image: url(../imgz/logo/logoCquake.png);
background-repeat: no-repeat;
}
EDIT:
Tried again, but with the second method listed here, still nothing. These are my current HTML and JS codes:
JS:
function SpriteAnim (options) {
var timerId,
i = 0,
element = document.getElementByClass(options.elementClass);
element.style.width = options.width + "px";
element.style.height = options.height + "px";
element.style.backgroundRepeat = "no-repeat";
element.style.backgroundImage = "url(" + options.sprite + ")";
timerId = setInterval(function () {
if (i >= options.frames) {
i = 0;
}
element.style.backgroundPosition = "0px -" + i * options.height + "px";
i ++;
}, 100);
this.stopAnimation = function () {
clearInterval(timerId);
};
}
var cupcake = new SpriteAnim({
width: 130,
height: 112,
frames: 30,
sprite: "..\imgz\logo\logoCquake.png",
elementClass : "logoCquake"
});
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script language="javascript" src="SpriteAnim.js">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<span class="ninja">Ninja </span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
my code seems to work:
<!doctype html>
<style>
div{background:url(http://i1243.photobucket.com/albums/gg555/Nyanja/logoCquake.png);height:33px;width:39px}
</style>
<div id=anim></div>
<script>
var i=0;
setInterval(function(){i+=33.6;document.getElementById("anim").style.backgroundPosition="0px "+i+"px"},100)
</script>
I believe 'span' tag being an inline element it either needs a 'display: block' property or 'float: left', i tried your code and it worked for me after i added 'display: block' to the 'span' tag with class 'logoCquake'. Hope this helps you.
Note: if you use 'display: block' the span will move to new line and if you use 'float: left' the 'span' tag will move to the left of the text.

Categories

Resources