dynamic image variable with onclick event - javascript

I have several canvases. I also have several picture URLs. I want to draw all pictures on the canvas. There is a problem in the drawing function. Drawing the image only works when the image loads completely, but I have to draw the image as it loads. I wrote following code:
for (var i = 2; i < length; i++) {
canvid[i] = "canv" + i;
img[i] = new Image();
img[i].src = "..\\images\\UploadImage\\"+ name + i + ".jpg";
img[i].onload = function () {
var c = document.getElementById(canvId[i]);
var cDraw = c.getContext("2d");
cDraw.drawImage(img[i], 0, 0);
};
I know this code has error, it's kind of pseudo code to show what I want.

Put your logic in
$(documet).ready(function(){
//logic
});

the answer is in following link
stack overflow link
when you want to call on click event on image variable you have to wait for it
so you couldn't use loop you have to put next call on previous image on load event .
var loadImages = function (imageURLarray) {
if (!(startPage < pages))
return;
canvid = "canv" + i;
img.src = imageURLarray[startPage];
// your top code
img.onload = function (e) {
// code, run after image load
var c = document.getElementById(canvid);
var cDraw = c.getContext("2d");
cDraw.drawImage(img, 0, 0);
startPage++;
loadImages(imageURLarray);
}
}
loadImages(imageURLarray);

Related

Blob images does not show up at UI, although I can see them on console

I am trying to create multiple blob images, and show them for a video timeline UI. To create the images, I take screenshots of the video for some certain time frames, and create img elements, then add img.src as blob images' url. The problem is blob images does not show up at UI, although I can see them on console. Any ideas?
Code snippet from creation of blob images:
// draw the video frame to canvas
const ctx = canvas.getContext("2d");
ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
ctx.canvas.toBlob(
blob => {
resolve(blob);
},
"image/jpeg",
0.75 /* quality */
);
Code Snippet from creation of images:
let img = '';
for (let i = 0; i < count / 3; i++) {
const cover = await GetVideoCover(item.video_url, i);
var url = URL.createObjectURL(cover);
var image = new Image();
image.src = url;
img += "<img src='"+image.src+"'>";
console.log(img)
}
return img;
The console log from console.log(img)line:
actual html img elements:
When I manually update the source as below, it works, but I did not understand why it does not get the source by itself. Any idea would be appreciated.
Try registering an onload event listener on the image element and then handle all code that depends on that image in the event listener, like so:
for (let i = 0; i < count / 3; i++) {
const cover = await GetVideoCover(item.video_url, i);
var url = URL.createObjectURL(cover);
var image = new Image();
image.src = url;
image.addEventListener('load', (event) => {
// perform some magic here e.g append to DOM or draw the image to canvas
}
}
Thank you for the contributions, the answers did not work but they helped me in the process. I solved the problem today and wanted to share it here.
I should have mentioned before as the created images are fed to vis.js.
When I experimented more, I saw vis.js does not append the created objects, but it changes the innerHTML of the timeline. (vis.js might not support blob images as src of img tag)
Then, I decided to give a shot to append element. To do that, I created a new div element, and appended the created images to that div.
I also added an additional promise level to the blob image creation process, since some files were missing.
Code snippet from newly added promise level:
const blobToImage = (itemVideoURL,captureSecond) => {
return new Promise(async (resolve,reject)=> {
let cover = await GetVideoCover(itemVideoURL,captureSecond);
const url = URL.createObjectURL(cover)
let img = new Image()
img.onload = () => {
URL.revokeObjectURL(url)
resolve(img)
}
img.src = url
img.height = '75'
})
}
Code snippet from new function:
let divElement = document.createElement('div');
for (let i = 0; i < count * 3; i++) {
let newImage = await blobToImage(item.video_url,i+1)
divElement.appendChild(newImage)
}
return divElement;
It magically worked.
You should use a single image rather than multiple images.
Just concatanate all images together :
let imgEle1 = document.querySelectorAll(".image")[0];
let imgEle2 = document.querySelectorAll(".image")[1];
let resEle = document.querySelector(".result");
var context = resEle.getContext("2d");
let BtnEle = document.querySelector(".Btn");
BtnEle.addEventListener("click", () => {
resEle.width = imgEle1.width;
resEle.height = imgEle1.height;
context.globalAlpha = 1.0;
context.drawImage(imgEle1, 0, 0);
context.globalAlpha = 0.5;
context.drawImage(imgEle2, 0, 0);
});

Using previous and next buttons to cycle through images in javascript

I'm writing a small mobile application using Javascript.
I'm making calls to a remote API that responds with some JSON formatted data. Within that data are URLs for images of products i need to display in my app. I've parsed the JSON into a JS array and now have an array of all the URLs for the images. When i first load my app i have a canvas which is used to display the first image from the array. I have two buttons, a previous and a next. I'd like to be able to cycle through the images using these buttons by using the URLs in the array to draw onto the canvas.
Any ideas?
Is something like the following what you're looking for?
// Image URLs
var imageUrls = ['http://emojipedia-us.s3.amazonaws.com/cache/8b/bd/8bbd3405b0a197214e229428c23dbe60.png', 'http://emojipedia-us.s3.amazonaws.com/cache/05/d1/05d1ba284ee1a3bfe4e0f68988baafb9.png', 'http://emojipedia-us.s3.amazonaws.com/cache/99/4c/994c5997c7a509703cc53ec2000bb258.png', 'http://emojipedia-us.s3.amazonaws.com/cache/59/0c/590c832e73a472c416bf9d8bfdd02a4a.png'];
// Keep track of the index of the image URL in the array above
var imageShownIndex = 0;
// Create a canvas
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
canvas.height = 150;
canvas.width = 150;
// Create a button that will load the previous image on the canvas when clicked
var previousButton = document.createElement('button');
previousButton.innerHTML = 'Previous Image';
previousButton.onclick = function () {
// Show images in a cycle, so when you get to the beginning of the array, you loop back to the end
imageShownIndex = (imageShownIndex==0) ? imageUrls.length-1 : imageShownIndex-1;
updateImage();
};
// Do same for the next button
var nextButton = document.createElement('button');
nextButton.innerHTML = 'Next Image';
nextButton.onclick = function () {
imageShownIndex = (imageShownIndex == imageUrls.length-1) ? 0 : imageShownIndex+1;
updateImage();
};
document.body.appendChild(previousButton);
document.body.appendChild(canvas);
document.body.appendChild(nextButton);
// Show the first image without requiring a click
updateImage();
function updateImage() {
// Create the Image object, using the URL from the array as the source
// You could pre-load all the images and store them in the array, rather than loading each image de novo on a click
var img = new Image();
img.src = imageUrls[imageShownIndex];
// Clear the canvas
canvasContext.clearRect(0, 0, 150, 150);
// After the image has loaded, draw the image on the canvas
img.onload = function() {
canvasContext.drawImage(img, 0, 0);
}
}
EDIT: Or if you have HTML elements already made, you can just use JavaScript to control the canvas. E.g.:
<html>
<body>
<button id="previous_button" onclick="goToPreviousImage()">Previous Image</button>
<canvas id="image_canvas" height=150, width=150></canvas>
<button id="next_button" onclick="goToNextImage()">Next Image</button>
</body>
<script>
var imageUrls = ['http://emojipedia-us.s3.amazonaws.com/cache/8b/bd/8bbd3405b0a197214e229428c23dbe60.png', 'http://emojipedia-us.s3.amazonaws.com/cache/05/d1/05d1ba284ee1a3bfe4e0f68988baafb9.png', 'http://emojipedia-us.s3.amazonaws.com/cache/99/4c/994c5997c7a509703cc53ec2000bb258.png', 'http://emojipedia-us.s3.amazonaws.com/cache/59/0c/590c832e73a472c416bf9d8bfdd02a4a.png'];
var imageShownIndex = 0;
var canvas = document.getElementById('image_canvas');
var canvasContext = canvas.getContext('2d');
function goToPreviousImage() {
imageShownIndex = (imageShownIndex==0) ? imageUrls.length-1 : imageShownIndex-1;
updateImage();
};
function goToNextImage() {
imageShownIndex = (imageShownIndex == imageUrls.length-1) ? 0 : imageShownIndex+1;
updateImage();
};
updateImage();
function updateImage() {
var img = new Image();
img.src = imageUrls[imageShownIndex];
canvasContext.clearRect(0, 0, 150, 150);
img.onload = function() {
canvasContext.drawImage(img, 0, 0);
}
}
</script>
</html>

Random image appear when website is loaded

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.
You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/
1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

Canvas ctx.drawimage() not working [duplicate]

This question already has an answer here:
Canvas: drawImage not drawing image to canvas
(1 answer)
Closed 8 years ago.
I am trying to render some pictures into a canvas, but when I use my rendering function, the images won't appear. The function is:
function populateSquareImages(){
for(var i = 0,ii = squares.length; i < ii; i++) {
if(squares[i].hasImage) {
var img = new Image();
img.src = "../Content/Squares/images/square_" + squares[i].uniqueId + ".png";
context.drawImage(img, squares[i].x, squares[i].y);
}
}
}
After some debugging, I am sure that x and y are accurate. The image file path is correct as well. Any idea of what might be wrong here?
You need to wait for the image to load before attempting to draw it. This should work:
function populateSquareImages () {
for (var i = 0, ii = squares.length; i < ii; i++) {
if (squares[i].hasImage) {
var img = new Image(),
square = squares[i];
img.src = "../Content/Squares/images/square_" + squares[i].uniqueId + ".png";
img.onload = function () {
context.drawImage(img, square.x, square.y);
};
}
}
}
The variable i will not be correct inside the callback function by the time it gets called, so store the value of squares[i] in another variable called square.

draw image on canvas after load into array

I tried to create an array of Image to be displayed on a canvas, after each image is loaded. No errors, no draw...
var x=...
var y=...
var canvas = document.getElementById(sCanvasName);
var context = canvas.getContext('2d');
var imageCardObj = [];
//vCards contains the images file names
for (var k=0;k<vCards.length;k++){
imageCardObj[k] = new Image();
var func = function(){
var c = arguments[3];
try{
c.drawImage(arguments[0], arguments[1], arguments[2]);
}catch(e){
alert(e.message)
}
}
imageCardObj[k].onload = func(imageCardObj[k], x, y, context);
imageCardObj[k].src = "res/img/"+vCards[k].trim()+".png";
x+=40;
}
You are calling the func() handler and gives the result to it to the image's onload handler. That won't work so well.. and you cannot pass arguments that way to a handler function.
Try this:
var func = function(){
// "this" will be the current image in here
var c = arguments[3];
try{
c.drawImage(this, x, y); // you need to reference x and y
}catch(e){
alert(e.message)
}
}
imageCardObj[k].onload = func; // only a reference here
If you need different x and y's then you need to maintain those on the side, either in an additional array or use objects to embed the image, its intended x and y and use the url to identify the image in question inside the func() callback.
Also note that load order may vary as the last image loaded could finish before the first one so when you draw the image they may not appear in the same order.
You may want to do this instead:
var files = [url1, url2, url, ...],
images = [],
numOfFiles = files.length,
count = numOfFiles;
// function to load all images in one go
function loadImages() {
// go through array of file names
for(var i = 0; i < numOfFiles; i++) {
// create an image element
var img = document.createElement('img');
// use common loader as we need to count files
img.onload = imageLoaded;
//img.onerror = ... handle errors too ...
//img.onabort = ... handle errors too ...
img.src = files[i];
// push image onto array in the same order as file names
images.push(img);
}
}
function imageLoaded(e) {
// for each successful load we count down
count--;
if (count === 0) draw(); //start when all images are loaded
}
Then you can start the drawing after the images has loaded - the images are now in the same order as the original array:
function draw() {
for(var i = 0, img; img = images[i++];)
ctx.drawImage(img, x, y); // or get x and y from an array
}
Hope this helps!
This is the final (working) version
var x=...
var y=...
var canvas = document.getElementById(sCanvasName);
var context = canvas.getContext('2d');
var imageCardObj = [];
for (var k=0;k<vCards.length;k++){
imageCardObj[k] = new Image();
imageCardObj[k].xxx=x;
var func = function(){
try{
context.drawImage(this, this.xxx, yStreet);
}catch(e){
alert(e.message)
}
}
imageCardObj[k].onload = func;
imageCardObj[k].src = 'res/img/'+vCards[k].trim()+".png";
x +=40;

Categories

Resources