how to load multiple image one by one on canvas? using loop - javascript

var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];
function sava(){
//push to array for loop
$('.Jicon').each(function(){
retval.push($(this).attr('id'));
retvalsrc.push($(this).attr('src'));
})
var className = $(".Jicon");
var classnameCount = className.length;
//loop classname
for(var d = 0; d < classnameCount; d++){
updateCanvas(retval[d], retvalsrc[d]);
}
}
//change main image
function updateCanvas(_id, _src)
{
ImgCanvas.clear();
// var oImg = new fabric.Image(_src, {
fabric.Image.fromURL(_src, function(oImg) {
oImg.setWidth(500);
oImg.setHeight(400);
oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
oImg.top = 50;
oImg.selectable = false;
ImgCanvas.add(oImg);
ImgCanvas.renderAll();
});
}
i have a mutiplete Image which i wanna to load them to canvas one by one using loop , how do i achieve that ? so when i press sava the image will show one by one on the canvas.i tried to use for but it load all those image together.
can anyone give me a help here~ thank apreciate.
Demo

Let the end of the imageFromURL call the next load, and refactor the code for use a settimeout, otherwise everything will be very fast.
The images before appeared all togheter because the load is async. So with the for loop you were
rapidly starting the loading in sequence of 4 images
immediately clear 4 times a canvas that is still empty
every image will then finish loading and appear on the canvas on random order.
var ImgCanvas = new fabric.Canvas("mycanvas");
var json = {};
var IdStore = [];
var retval = [];
var retvalsrc = [];
function sava(){
$('.Jicon').each(function(){
retval.push($(this).attr('id'));
retvalsrc.push($(this).attr('src'));
})
updateCanvas();
}
//change main image
function updateCanvas() {
ImgCanvas.clear();
var _src = retvalsrc.pop();
fabric.Image.fromURL(_src, function(oImg) {
oImg.setWidth(500);
oImg.setHeight(400);
oImg.left = ((ImgCanvas.width/2)-(oImg.width/2));
oImg.top = 50;
oImg.selectable = false;
ImgCanvas.add(oImg);
ImgCanvas.renderAll();
if (retvalsrc.length > 0) {
setTimeout(updateCanvas, 1000);
}
});
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<img name="001.png" class="Jicon" id="displayImage1" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/077.png" onclick="updateCanvas(this.src);">
<img name="002.png" class="Jicon" id="displayImag2" src="http://i795.photobucket.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/076.png" onclick="updateCanvas(this.src);">
<img name="003.png" class="Jicon" id="displayImage3" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/071.png~c100" onclick="updateCanvas(this.src);">
<img name="004.png" class="Jicon" id="displayImag4" src="http://rs795.pbsrc.com/albums/yy232/PixKaruumi/Pokemon%20Pixels/072.png~c100" onclick="updateCanvas(this.src);">
</div>
<button onclick="sava();">sava</button>
<div id="warpper">
<canvas id="mycanvas" width="380" height="500" style="border:1px solid #000;"></canvas>
</div><!-- end of div -->
</body>

Related

hyperlinking an image in an array from another array

I have 2 arrays,I with images and another with links.
Using set interval I am changing the image in 2000millisec.
How can I hyperlink the image with the links.
var img_array = <?php echo json_encode($images); ?>;
var link_array = <?php echo json_encode($links); ?>;
var image = document.getElementById("aaa");
var index=0;
function slide(){
document["aaa"].src = img_array[index];
index++;
if(index>=img_array.length)
{
index=0;
}
}
setInterval("slide()",2000);
</script>
Here's an example. It's not perfect, because if you see it in the first time, the image is not loaded. This is why most of the sites generates all the images with links, and then just hide and show them.
var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
var link = document.getElementById("link");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;
function slide(){
image.src = img_array[index];
link.href = link_array[index];
index++;
if(index >= img_array.length) {
index=0;
}
}
setInterval(slide, 2000);
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" width="200">
Or if you can't change the DOM or you want to hide somewhy the url you can do something like this:
var img_array = ["https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg", "https://images.pexels.com/photos/46710/pexels-photo-46710.jpeg", "https://images.unsplash.com/photo-1529736576495-1ed4a29ca7e1"];
var link_array = ["index1.html","index2.html","index3.html"];
var image = document.getElementById("image");
// The first (which is the 0) is already loaded, so we need to skip it from here.
var index = 1;
function slide(){
image.src = img_array[index];
index++;
if(index >= img_array.length) {
index=0;
}
}
image.addEventListener("click", function() {
// This is because of the sandbox environment.
console.log(link_array[index]);
// This is what you need.
window.open(link_array[index]);
});
setInterval(slide, 2000);
.pointer {
cursor: pointer;
}
<img src="https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg" id="image" class="pointer" width="200">
However in this case maybe you will get blocked by the browser or if the click was registered after the new image was loaded, it may create a missclick.

How to select images in array to fade in and out

var n=0;
var images=["FullSizeRender (1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
$(document).ready(function() {
// Change image
$("#himg").click(function(){
n++;
if(n==images.length){
n=0;
};
document.getElementById("himg").src=images[n];
$("#himg").find('img[src="' + images[n] + '"]').fadeOut();
$("#himg").find('img[src="' + images[n+1] + '"]').hide().fadeIn();
});
<div class="col-xs-2">
<div id="handbags">
<h4>Handbags</h4>
<img id="himg" src="FullSizeRender (1).jpg" />
</div>
</div>
I have made an array where images change on click, but I am trying to make the images fade on click instead of sharply changing. I've tried selecting the images by source using the index from the array, but it's not working.
Try this:
$(document).ready(function() {
var n = 0;
var images = ["FullSizeRender(1).jpg","IMG_1875.JPG","IMG_4665.JPG","IMG_5213.JPG"];
var image = $('#himg');
image.on('click', function() {
var newN = n+1;
if (newN >= images.length) { newN = 0 };
image.attr('src', images[n]);
image.fadeOut(300, function () {
image.attr('src', images[newN]);
image.fadeIn();
n = newN;
});
});
});

JavaScript Image Swap with a Timer and Fade

I have a unique situation where I am trying to take an image and swap it out after a specific time. I have that part working however I also need the pictures to fade in and out of each other and I can not figure that part out. Please help if you can.
JavaScript:
<script type="text/javascript">
var picPaths = ['images/Front1.jpg','images/Front2.jpg','images/Front3.jpg'];
var curPic = -1;
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage,5000);
}
window.onload=function() {
imgCont = document.getElementById('imgBanner');
swapImage();
}
</script>
HTML:
div img id="imgBanner" src="" alt="" / /div
I have the correct <> in places on the HTML however it would not let me post the HTML into the screen.

Why doesn't this mouseover/rollover work?

I have 3 images (pic1, pic2, pic3) that on click of the div ID change to (pic4, pic5, pic6). All this works fine but I need to put in a mouseover command that when hovering over pic2, it changes to pic 7 and on mouseout it goes back to pic 2. I am unsure as to why this part of my code isn't working, is it a syntax error? The two functions I am trying to use to do this are "rolloverImage" and "init".
HTML
<div id="content1">
<img src="pic1.jpg" alt="pic1"/>
<img src="pic2.jpg" alt="pic2" id="pic2"/>
<img src="pic3.jpg" alt="pic3"/>
</div>
Javascript
var g = {};
//Change background colors every 20 seconds
function changebackground() {
var backColors = ["#6AAFF7", "#3AFC98", "#FC9B3A", "#FF3030", "#DEDEDE"];
var indexChange = 0;
setInterval(function() {
var selectedcolor = backColors[indexChange];
document.body.style.background = selectedcolor;
indexChange = (indexChange + 1) % backColors.length;
}, 20000);
}
function rolloverImage(){
if (g.imgCtr == 0){
g.pic2.src = g.img[++g.imgCtr];
}
else {
g.pic2.src = g.img[--g.imgCtr];
}
}
function init(){
g.img = ["pic2.jpg", "pic7.jpg"];
g.imgCtr = 0;
g.pic2 = document.getElementById('pic2');
g.pic2.onmouseover = rolloverImage;
g.pic2.onmouseout = rolloverImage;
}
window.onload = function() {
var picSets = [
["pic1.jpg", "pic2.jpg", "pic3.jpg"],
["pic4.jpg", "pic5.jpg", "pic6.jpg"],
];
var currentSetIdx = 0;
var contentDiv = document.getElementById("content1");
var images = contentDiv.querySelectorAll("img");
refreshPics();
contentDiv.addEventListener("click", function() {
currentSetIdx = (currentSetIdx + 1) % picSets.length;
refreshPics();
});
function refreshPics() {
var currentSet = picSets[currentSetIdx];
var i;
for(i = 0; i < currentSet.length; i++) {
images[i].src = currentSet[i];
}
}
changebackground();
init();
}

How to choose random image from image set in javascript

I have been using the following code to generate random images, but none of the pictures are showing up.
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
var theImages = new Array()
theImages[0] = '<img class="atvi-image-image" alt=""src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png" title="" height="467" width="675">'
theImages[1] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png" title="" height="732" width="1084">'
theImages[2] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-extra-slots.png" title="" height="480" width="752">'
theImages[3] = '<img class="atvi-image-image" alt="" src="/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-2025.png" title="" height="412" width="683">'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write(theImages[whichImage]);
}
</script>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
</body>
</html>
Thank you in advance for your help!
You already have the full <img> tag in the array. So just use:
document.write(theImages[whichImage]);
Although I would advise against using document.write. Of course, in your situation, where it's being executed in the middle of HTML, I don't see much of a problem. It would be bad if document.write were executed after the page was rendered. Normally, the preferred method is something like the appendChild method or even setting innerHTML, although it would take some refactoring to get your code to use them.
Here's an example of how I'd set it up:
(function () {
var theImages = [{
src: "http://www.techinasia.com/techinasia/wp-content/uploads/2009/12/smile.png",
width: "675",
height: "467"
}, {
src: "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdcHlJqgIKNOS0DaEjO31xK1zYtmJlza8z70ljiKFbo2ZgLdh9eA",
width: "1084",
height: "732"
}, {
src: "http://cdn2-b.examiner.com/sites/default/files/styles/large_lightbox/hash/68/d1/68d11ab242d40c8d5abbe8edb58fd4ed_0.jpg?itok=M3qtK47_",
width: "200",
height: "200"
}];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.getRandomImage = function () {
var whichImage = getRandomInt(0, preBuffer.length - 1);
return preBuffer[whichImage];
}
})();
window.onload = function () {
var newImage = getRandomImage();
console.log(newImage);
document.body.appendChild(newImage);
};
DEMO: http://jsfiddle.net/wFjGv/
This code uses a new object to hold the details for each image. That way, you can easily set and get each image's properties that you need without hardcoding HTML.
It preloads the images in the preBuffer array, and when needed, an image is retrieved from the array, and put into the <body>. You can change its target in the onload event. The getRandomImage function returns a random image from that array. I updated the method of getting a random integer as well.
You are setting an <img src= something that is not what you want. Your array (theImages) is storing full <img> tags, not just the link to that image.
Either change you theImages array to store values like so:
theImages[0] = "/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png"
OR use the current setup as the image tag.
document.write(theImages[whichImage]);
Also:
With random numbers, you should probably stick to Math.floor() lest
you round over your max length.
var j = 0 is missing a ;
theImages img tags are not closed (<img ... />
Try this-
var srcs = [
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-calling-card-flags.png",
"/content/dam/atvi/callofduty/blackops2/cod-bo2/dlc/mdlc-nuketown-zombies.png",
"foo/bar.jpg"
], imgs = [];
function init() {
"use strict";
var i, x, div;
div = document.createElement('div');
div.id = 'imageContainer';
document.querySelector('body').appendChild(div);
for (i = 0; i < srcs.length; i += 1) {
x = new Image();
x.src = srcs[i];
imgs.push(x);
}
}
function showRandom() {
"use strict";
document.querySelector('#imageContainer').innerHTML = imgs[Math.random * imgs.length];
}
init();
To add a random image-
showRandom();
PS - You shouldn't use document.write, but if you do, you should close the stream by document.close, to tell the browser to finish loading the page. Read more - MDN JS Docs

Categories