Issue with displaying images in JavaScript(DOM) - javascript

My task is to add 5 images (smile.png) to 5 randomly positions in the left half of the page which is a div with id="leftSide" and size 500x500px
so here is my code
var numberOfFaces = 5;
var theLeftSide = document.getElementById("leftSide");
var count = 0;
function generateFaces(){
while(count < numberOfFaces) {
var this_img=createElement("img");
this_img.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
var toppos = Math.random() * 400;
var top_pos = Math.floor(toppos);
var leftpos = Math.random() * 400;
var left_pos = Math.floor(leftpos);
this_img.style.left=left_pos + "px";
this_img.style.top=top_pos + "px";
theLeftSide.appendChild(this_img);
count+=1;
}
}
img {
position:absolute
}
div {
position:absolute;
width:500px;
height:500px;
}
#rightSide {
left: 500px;
border-left: 1px solid black;
}
<body onload="generateFaces()">
<h1>Matching game</h1>
<p>Click on the extra smiling face on the left.</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
It should do
this
But instead it shows just a white page.

Change createElement to new Image();
var this_img=new Image();

Related

When I try to create two slider boxes on the same page, it doesn't work

Source
I tried creating table and copying the html over and it didn't work. I'm trying to create some before and afters. I'm not 100% on Javascript, but I'm thinking there is something in there preventing it.
Sorry I have to link to the code. It would not let me post with so much copypasta'd code.
Example of sliders working using the same HTML except for the images. Added table and removed CSS that was sizing the images.
function initComparisons() {
var x, i;
/*find all elements with an "overlay" class:*/
x = document.getElementsByClassName("img-comp-overlay");
for (i = 0; i < x.length; i++) {
/*once for each "overlay" element:
pass the "overlay" element as a parameter when executing the compareImages function:*/
compareImages(x[i]);
}
function compareImages(img) {
var slider, img, clicked = 0,
w, h;
/*get the width and height of the img element*/
w = img.offsetWidth;
h = img.offsetHeight;
/*set the width of the img element to 50%:*/
img.style.width = (w / 2) + "px";
/*create slider:*/
slider = document.createElement("DIV");
slider.setAttribute("class", "img-comp-slider");
/*insert slider*/
img.parentElement.insertBefore(slider, img);
/*position the slider in the middle:*/
slider.style.top = (h / 2) - (slider.offsetHeight / 2) + "px";
slider.style.left = (w / 2) - (slider.offsetWidth / 2) + "px";
/*execute a function when the mouse button is pressed:*/
slider.addEventListener("mousedown", slideReady);
/*and another function when the mouse button is released:*/
window.addEventListener("mouseup", slideFinish);
/*or touched (for touch screens:*/
slider.addEventListener("touchstart", slideReady);
/*and released (for touch screens:*/
window.addEventListener("touchstop", slideFinish);
function slideReady(e) {
/*prevent any other actions that may occur when moving over the image:*/
e.preventDefault();
/*the slider is now clicked and ready to move:*/
clicked = 1;
/*execute a function when the slider is moved:*/
window.addEventListener("mousemove", slideMove);
window.addEventListener("touchmove", slideMove);
}
function slideFinish() {
/*the slider is no longer clicked:*/
clicked = 0;
}
function slideMove(e) {
var pos;
/*if the slider is no longer clicked, exit this function:*/
if (clicked == 0) return false;
/*get the cursor's x position:*/
pos = getCursorPos(e)
/*prevent the slider from being positioned outside the image:*/
if (pos < 0) pos = 0;
if (pos > w) pos = w;
/*execute a function that will resize the overlay image according to the cursor:*/
slide(pos);
}
function getCursorPos(e) {
var a, x = 0;
e = e || window.event;
/*get the x positions of the image:*/
a = img.getBoundingClientRect();
/*calculate the cursor's x coordinate, relative to the image:*/
x = e.pageX - a.left;
/*consider any page scrolling:*/
x = x - window.pageXOffset;
return x;
}
function slide(x) {
/*resize the image:*/
img.style.width = x + "px";
/*position the slider:*/
slider.style.left = img.offsetWidth - (slider.offsetWidth / 2) + "px";
}
}
}
/*Execute a function that will execute an image compare function for each element with the img-comp-overlay class:*/
initComparisons();
div[class^="img-comp-container"] {
position: relative;
}
* {
box-sizing: border-box;
}
.img-comp-img {
position: absolute;
width: auto;
height: auto;
overflow: hidden;
}
.img-comp-img img {
display: block;
vertical-align: middle;
}
.img-comp-slider {
position: absolute;
z-index: 9;
cursor: ew-resize;
/*set the appearance of the slider:*/
width: 40px;
height: 40px;
background-color: #2196F3;
opacity: 0.7;
border-radius: 50%;
}
<table class="cool" cellpadding="10">
<tr>
<td width="500">
<div class="img-comp-container1">
<div class="img-comp-img">
<img src="http://placekitten.com/500/400" width="500" height="400">
</div>
<div class="img-comp-img img-comp-overlay">
<img src="http://placebear.com/500/400" width="500" height="400">
</div>
</div>
</td>
<td>
<div class="img-comp-container2">
<div class="img-comp-img">
<img src="http://placekitten.com/500/300" width="500" height="300">
</div>
<div class="img-comp-img img-comp-overlay">
<img src="http://baconmockup.com/500/300/" width="500" height="300">
</div>
</div>
</td>
</tr>
</table>

appendChild removes style

I tried to use appendChild function in order to create a new image node with some style properties. After using it, all properties vanishes. The images supposed to be randomly positioned on the leftSide div, however, actually, they are put align in a row.
<html>
<head>
<title>Matching Game</title>
<style>
#rightSide {
position: absolute;
left: 700px;
border-left: 1px solid black;
width:700px;
height:700px;
}
#leftSide {
width:700px;
height:700px;
position: absolute;
}
</style>
</head>
<body onload="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left</p>
<div id='leftSide'>
</div>
<div id='rightSide'>
</div>
<script>
var numberOfFaces = 5;
var theLeftSide = document.getElementById('leftSide');
var generateFaces = function() {
for(var i = 0; i < numberOfFaces; i++)
{
var img = document.createElement('img');
img.src = 'smile.png';
img.style.top = Math.floor(Math.random()*600);
img.style.left = Math.floor(Math.random()*600);
theLeftSide.appendChild(img);
}
}
</script>
</body>
</html>
http://i.stack.imgur.com/fZaYA.png
Math.floor(Math.random()*600); is going to return a number. Unless the value is 0, the CSS left and top properties require a length. Lengths have units.
Additionally, you haven't changed the position property away from static, so the left and top properties will have no effect as they apply only to positioned elements.
that should solve your problem.
var img = document.createElement('img');
img.style.top = Math.floor(Math.random()*600) + 'px';

How to copy nodes from an existing div into another div Javascript

Im not sure what im doing wrong, but iv created 5 images placed at random positions in the left div and i want to copy all 5 - the firstchild and place them on the right side. So il have 5 images on the left and 4 on the right. I debugged my if with alert and it does run, but i cant figure out what wrong with my code? Why is it not print images to the right hand side? Any help is appreciated thank you
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
facesNeeded = 5;
totalfFaces = 0;
function makeFaces() {
while(facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces){
alert("hi");
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.childNode[0]);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
}
<!DOCTYPE html>
<html>
<head>
<style>
img{
position: absolute;
}
div {
position: absolute;
width:500px;
height:500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
<script src="script3.js"></script>
</head>
<body onload="makeFaces()">
<h1> Matching Game</h1>
<p> Click on the extra smiling face on the left</p>
<div id="leftside"></div>
<div id="rightside"></div>
</body>
</html>
You have a typo in this line:
leftSideImages.removeChild(leftSideImages.childNode[0]);
it should be:
leftSideImages.removeChild(leftSideImages.childNodes[0]);
Full code:
var theLeftSide = document.getElementById("leftside");
var theRightSide = document.getElementById("rightside");
facesNeeded = 5;
totalfFaces = 0;
function makeFaces() {
while(facesNeeded != totalfFaces) {
smiley = document.createElement("img");
smiley.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smiley.style.top = Math.random() * 401 + "px";
smiley.style.left = Math.random() * 401 + "px";
document.getElementById("leftside").appendChild(smiley);
totalfFaces++;
// alert(totalfFaces); used to debug
}
if (facesNeeded == totalfFaces){
alert("hi");
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.childNodes[0]);
document.getElementById("rightside").appendChild(leftSideImages);
//alert("hi");
}
}
<!DOCTYPE html>
<html>
<head>
<style>
img{
position: absolute;
}
div {
position: absolute;
width:500px;
height:500px;
}
#rightside {
left: 500px;
border-left: 1px solid black;
}
</style>
<script src="script3.js"></script>
</head>
<body onload="makeFaces()">
<h1> Matching Game</h1>
<p> Click on the extra smiling face on the left</p>
<div id="leftside"></div>
<div id="rightside"></div>
</body>
</html>

Sudden change in picture quality in html canvas

I am making a canvas project and using some .png pictures. I used it in one file, canvas drew it up perfectly and all was well. But when i tried to to the same thing in a different file the quality of the pictures sank for no apparent reason. Would love some help/explenation to why this occured!
Here are the difference in coding, just open the files to see the difference in quality.
"Good quality code"
<!DOCTYPE html>
<html>
<head>
<title>Övning 1</title>
<style type="text/css">
*,body{
margin: 0px;
padding: 0px;
text-align: center;
background:url('bilder/background.png');
}
canvas{
border: 1px #999999 solid;
margin-top: 50px;
box-shadow: 2px 2px 1px rgba(50, 50, 50, 0.75) inset;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="900" height="400"></canvas>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var path = "bilder/helnot.png";
var image1 = new DragImage(path, 200, 100);
var image2 = new DragImage(path, 300, 100);
var gKlav = new Image();
gKlav.src = "bilder/g-klav.png";
var loop = setInterval(function() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0, 0, 900, 400);
image1.update();
image2.update();
}, 30);
var mouseX = 0;
var mouseY = 0;
var mousePressed = false;
var dragging = false;
function DrawLines(){
ctx.fillStyle = "#000000";
ctx.fillRect(50,160,800,1);
ctx.fillRect(50,180,800,1);
ctx.fillRect(50,200,800,1);
ctx.fillRect(50,220,800,1);
ctx.fillRect(50,240,800,1);
ctx.drawImage(gKlav, 40, 40);
}
//Saves the cursers location into two vairables
$(document).mousemove(function(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
})
//Specifies what happens when the mouse is clicked
$(document).mousedown(function() {
mousePressed = true;
}).mouseup(function() {
mousePressed = false;
dragging = false;
});
//'this.x' and 'that.x' refers to the location of the top left corner of the image.
//'startX' and 'startY' refers to the distance between the curser and the image.
function DragImage(src, x, y) {
var that = this;
var startX = 0;
var startY = 0;
var drag = false;
this.x = x;
this.y = y;
var img = new Image();
img.src = src;
this.update = function() {
if (mousePressed) {
var left = that.x;
var right = that.x + img.width;
var top = that.y;
var bottom = that.y + img.height;
if (!drag) {
startX = mouseX - that.x;
startY = mouseY - that.y;
}
if (mouseX < right && mouseX > left && mouseY < bottom && mouseY > top) {
if (!dragging){
dragging = true;
drag = true;
}
}
} else {
drag = false;
$(document).mouseup(function(){
if((that.y + (img.height/2)) > 145 && (that.y + (img.height/2)) < 155){that.y = 140}
if((that.y + (img.height/2)) > 155 && (that.y + (img.height/2)) < 165){that.y = 150}
if((that.y + (img.height/2)) > 165 && (that.y + (img.height/2)) < 175){that.y = 160}
if((that.y + (img.height/2)) > 175 && (that.y + (img.height/2)) < 185){that.y = 170}
if((that.y + (img.height/2)) > 185 && (that.y + (img.height/2)) < 195){that.y = 180}
if((that.y + (img.height/2)) > 195 && (that.y + (img.height/2)) < 205){that.y = 190}
});
}
//Makes the image 'drag' across the screen.
if (drag) {
that.x = mouseX - startX;
that.y = mouseY - startY;
}
ctx.drawImage(img, that.x, that.y);
DrawLines();
}
}
</script>
</body>
</html>
"Bad quality code"
<!DOCTYPE html>
<html>
<head>
<title>Övning 2</title>
<style type="text/css">
*,body{
margin: 0px;
padding: 0px;
text-align: center;
background:url('bilder/background.png');
}
canvas{
border: 1px #999999 solid;
margin-top: 50px;
box-shadow: 2px 2px 1px rgba(50, 50, 50, 0.75) inset;
}
button{
white-space:nowrap;
display:inline-block;
position:relative;
background:#C22E3A;
border:1px black solid;
text-decoration:none;
color:white;
padding: 6px 9px;
border-radius:3px;
margin:5px;
padding-left:50px;
padding-right: 50px;
-webkit-box-shadow: 0 5px 1px rgba(0,0,0,0.2);
text-shadow: 0px -1px 0px rgba(0,0,0,0.5);
transition: background-color linear 0.07s;
}
button:active{
top:3px;
-webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.3);
}
#inputBox{
display: none;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="900" height="400"></canvas><br />
<button id="start" onclick="Activate()">Start</button><br />
<input type="text" id="inputBox">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var start = false;
var helnot = "bilder/helnot.png";
var helnot2 = new RandomizeNote(helnot);
var gKlav = new Image();
gKlav.src = "bilder/g-klav.png";
var loop = setInterval(function() {
if(start){
document.getElementById('start').style.display = "none";
document.getElementById('inputBox').style.display = "inline";
helnot2.update();
}
Sheet();
}, 30);
function Sheet(){
ctx.fillStyle = "#000000";
ctx.fillRect(200,160,500,1);
ctx.fillRect(200,180,500,1);
ctx.fillRect(200,200,500,1);
ctx.fillRect(200,220,500,1);
ctx.fillRect(200,240,500,1);
ctx.drawImage(gKlav, 200, 150);
}
function Activate(){
start = true;
}
function RandomizeNote(src){
var img = new Image();
img.src = src;
this.update = function(){
ctx.drawImage(img, 430, 150);
}
}
</script>
</body>
</html>

javascript onmousedown and updating the location of an object

<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 320px;
height: 480px;
border: 1px solid red;
}
</style>
</head>
<body>
<div style="position: relative;" id="container">
<canvas id="myCanvas" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="plane" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="canvas2" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
<script>
var c=document.getElementById("myCanvas");
var c2=document.getElementById("canvas2");
var c3=document.getElementById("plane");
var plane;
var ground;
var score1 = "1"
var score = score1;
var increase = 6;
var delay = 40;
var scorez;
var fall = 0;
start();
function start(){
backgrounds();
var scorez = setInterval(scoring, delay);
setInterval(planeUpdate, delay);
setInterval(donwer, delay);
}
function backgrounds(){
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0, 280);
my_gradient.addColorStop(0,"white");
my_gradient.addColorStop(1,"blue");
ctx.fillStyle=my_gradient;
ctx.fillRect(0,0,320,480);
ground = c.getContext("2d");
ctx.fillStyle="black";
ctx.fillRect(0,450 , 320 ,30);
}
function scoring(){
scores();
score2();
}
function scores(){
score -= 3-(3+increase);
}
function score2(){
var context = c2.getContext('2d');
context.clearRect(0, 0, c2.width, c2.height);
var w = c2.width;
c2.width = 1;
c2.width = w;
var text=c2.getContext("2d");
text.font="20px Georgia";
text.fillText(score ,15,20);
var text=c2.getContext("2d");
text.font="20px Georgia";
text.fillText(fall ,40,40);
}
function hit(){
}
function loes(){
clearInterval(scorez);
}
plane = c3.getContext('2d');
var img = new Image();
img.src = "images/Plane.png"; //transparent png
function planeUpdate(){
var context = c3.getContext('2d');
context.clearRect(0, 0, c3.width, c3.height);
var w = c3.width;
c3.width = 1;
c3.width = w;
plane.drawImage(img, 40, fall, 50, 50);
}
function donwer(){
//myCanvas.onmousedown = function(e){
fall -= 1-2;
//}
}
</script>
<!--
http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png
--!>
</body>
</html>
So my issue is; is that I can not seem to get onmousedown function to work. Could somebody please suggest what I am doing wrong. Thank you. I would like the plan to move down when the mouse is not pressed and while the mouse is being held the plan to go up. Thank you.
myCanvas is undefined.
You already stored a reference to canvas#myCanvas with var c=document.getElementById("myCanvas");, so use c instead of myCanvas:
c.onmousedown = function(e){
fall -= 1-2;
}
Or you could use document.getElementById("myCanvas").onmousedown = ...

Categories