How to load images using web worker? - javascript

I am trying to load images using webworker api. I have large images in my html page its takes 5 mins to load all images therefore i am using webworker to load images.
here is technique..
I am keeping src attribute of all img tag empty in html page.
All images have unique id for each img e.g id = events_all_1_01 meaning image src will be "pictures/keywords/events/all/1/01.jpg". i.e last part events/all/1/01.jpg is id.
Main.html file
<body>
<script src="js/modernizr.custom.js"></script>
<script language="javascript">
window.onload = function(){
if (Modernizr.webworkers) {
var worker = new Worker('js/webworker/test_ww_23_04.js');
worker.onmessage = function(event) {
var url = event.data.replace(/_/g, "/");
var image_src = "pictures/keywords/"+url+".jpg";
var img = new Image();
img.src = image_src;
img.onload = function(){
// do stuff when your image is loaded
document.getElementById(event.data).src = image_src;
}
};
worker.onerror = function(e) {
alert('Error: Line ' + e.lineno + ' in ' + e.filename + ': ' + e.message);
};
var img_container = document.getElementById("wrapper");
var image_array = img_container.getElementsByTagName('img');
for(var i=0;i<image_array.length;i++){
var img_id = image_array[i].id;
console.log(img_id); // http://jsfiddle.net/5vyseob7/
postMessage(img_id); // http://jsfiddle.net/k04t6760/ here i am passing id one by one to webworker..
}
} // end of if condition
} // end of window.onload()
</script>
<div id="wrapper" style="height: 500px;width: 200px;overflow-y: auto;border: 1px solid gray;">
<div id="pictures1">
<div class="effect-1">
<div><img src="" id="events_all_1_01" width="150" height="100"></div>
<div><img src="" id="events_all_1_02" width="150" height="100"></div>
<div><img src="" id="events_all_1_03" width="150" height="100"></div>
<div><img src="" id="events_all_1_04" width="150" height="100"></div>
</div>
<hr/>
<div class="effect-2">
<div><img src="" id="events_all_2_01" width="150" height="100"></div>
<div><img src="" id="events_all_2_02" width="150" height="100"></div>
<div><img src="" id="events_all_2_03" width="150" height="100"></div>
<div><img src="" id="events_all_2_04" width="150" height="100"></div>
</div>
<hr/>
<div class="effect-3">
<div><img src="" id="events_all_3_01" width="150" height="100"></div>
<div><img src="" id="events_all_3_02" width="150" height="100"></div>
<div><img src="" id="events_all_3_03" width="150" height="100"></div>
<div><img src="" id="events_all_3_04" width="150" height="100"></div>
</div>
<hr/>
<div class="effect-4">
<div><img src="" id="events_all_4_01" width="150" height="100"></div>
<div><img src="" id="events_all_4_02" width="150" height="100"></div>
<div><img src="" id="events_all_4_03" width="150" height="100"></div>
<div><img src="" id="events_all_4_04" width="150" height="100"></div>
</div>
</div>
</div>
</body>
webworker code.
//var src = 'pictures/keywords/events/all/1/01.jpg';
//var id = src.substring(src.substring(0,18).length).split('.')[0].replace(/\//g, "_"); // Creating id here......events_all_1_01
//var fst = id.substring(0, id.lastIndexOf("_")+1); // get first part.... events_all_1
//var lst = parseInt(id.substr(id.lastIndexOf("_")+1)); // get last part i.e imagename ..01,02,03 etc....... and convert it to int
function LoadImages(currID) {
setTimeout(function() {
postMessage(currID);
}, 100);
}
self.onmessage = function(event) {
var currID = event.data;
LoadImages(currID);
};
I am getting following error :
Uncaught SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin '' in a call to 'postMessage'.

Typo error:
...
worker.onmessage = function(event) {
var url = e.data.replace(/_/g, "/");
e is not defined ... you probably meant function(e) or event.data.replace
UPDATE
Window don't have the postMessage method ... you need to use the worker method worker.postMessage

Related

How to add HTML append javascript... "quotation marks" problems

I'm trying to transform div content from img to div strong
for example
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>
I want to transform to div strong
<div class="multi-gallery-image show" id="service_preview">
<div><strong>チャイルドカット¥3000</strong></div>
<div><strong>ジュニアカット</strong></div>
<div><strong>トップスタイリストカット</strong></div>
<div><strong>Hair Styling</strong></div>
<div><strong>Manicures</strong></div>
<div><strong>Hair Coloring</strong></div>
</div>
I have this but the result is different as expected:
let servicePreview = document.getElementById('service_preview'); //parent where I am trying to introduce the src values
let myImg;
let mySrc;
let toPush;
if (servicePreview.getElementsByTagName('img').length > 0){
let servicesNumber = servicePreview.getElementsByTagName('img').length; //number of img tags inside the service_preview
for (let i = 0; i < servicesNumber; i++){
myImg = servicePreview.getElementsByTagName('img')[i]; //capturing the img tag
mySrc = myImg.getAttribute('src'); //capturing the src value from img tag
toPush = '<div><strong>' + mySrc + '</strong></div>'; //creating html tag for push to the parent service_preview
servicePreview.append(toPush); //appending the html tag
}
}
but the result of this is
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="トップスタイリストカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
"<div><strong>チャイルドカット¥3000</strong></div>"
"<div><strong>ジュニアカット</strong></div>"
"<div><strong>ハナコカット</strong></div>"
"<div><strong>トップスタイリストカット</strong></div>"
"<div><strong>Hair Styling</strong></div>"
"<div><strong>Manicures</strong></div>"
</div>
I want to delete that "quotes" on every div strong, that is a string.
I have to delete the complete img tag after solve the "quotes"
problem
use createElement to create dom element to appendChild and removeChild to remove elements.
let servicePreview = document.getElementById('service_preview');
var myImg;
var mySrc;
let toPush;
var elements = servicePreview.getElementsByTagName('img');
while (elements[0]) {
newDiv = document.createElement('div');
newStrong = document.createElement('strong');
newStrong.innerHTML = elements[0].getAttribute('src');
newDiv.appendChild(newStrong);
servicePreview.appendChild(newDiv);
elements[0].parentNode.removeChild(elements[0]);
}
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>
Unlike jQuery append() the native method treats html strings as text
Use insertAdjacentHTML(position, html) instead
const str = '<div class="inserted">Test</div>'
document.getElementById('one').append(str);// shows as text
document.getElementById('two').insertAdjacentHTML('beforeend', str)
.inserted{color:red}
<div id="one"></div>
<div id="two"></div>
In raw JavaScript I believe its something like this.
const services = ['チャイルドカット¥3000', 'ジュニアカット', 'ハナコカット',
'Hair Styling', 'Manicures', 'Hair Coloring']
const preview = document.getElementById("service_preview")
services.forEach(service =>{
const div = document.createElement("div")
const strong = document.createElement("strong")
strong.innerText = service
div.appendChild(strong)
preview.appendChild(div)
})
const servicePreview = document.getElementById("service_preview");
const imageSources = [...servicePreview.children].map((img) => img.src);
console.log(imageSources);
// Remove all images
while (servicePreview.firstChild) {
servicePreview.removeChild(servicePreview.firstChild);
}
// Add new div/strong tags
for (const imageSource of imageSources) {
const div = document.createElement("div");
const strong = document.createElement("strong");
strong.textContent = imageSource;
div.appendChild(strong);
servicePreview.appendChild(div);
}
simply use replaceChild() method
there is a trap with img.src because you get an URI
const servicePreview = document.getElementById('service_preview')
servicePreview.querySelectorAll('img').forEach(imgElm=>
{
let newDiv = document.createElement('div')
, newStrg = document.createElement('strong')
;
newDiv.appendChild( newStrg )
newStrg.textContent = imgElm.getAttribute('src') // or decodeURI( imgElm.src.split('/').pop() )
servicePreview.replaceChild( newDiv, imgElm )
})
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>

jquery update the anchor tag's image src based on query string value

How can I replace the image src on each of the elements?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="userShop">
<p class="shoppingbaskets">
<img src="image/empty.png" title="empty" width="50" height="50">
<img src="image/full.png" title="full" width="50" height="50">
<img src="image/semi.png" title="semi" width="50" height="50">
<img src="image/abandoned.png" title="abandoned" width="50" height="50">
<img src="image/completed.png" title="completed" width="50" height="50">
</p>
</div>
I want to replace the img src based on the query string basket value.
For example, if it is empty, then its image src will be newDir/newImageEmpty.jpg
here is my attempt:
var listStatus = [
{
'name': 'full',
'image': 'http://www.faredelbene.net/img/icon_stumble.png'
},
// and some more for others
];
listStatus.forEach(function (item){
$("#userShop a").each(function(link) {
if (item.name.indexOf(
new URL(this.href).searchParams.get("basket")
) !=-1) {
$(this).find("img").attr({src: item.image});
}
});
})
is this the correct approach?
There are many ways of doing this, in reality,
you should be able to do it just with some research on Google, but ah well.
let links = document.querySelectorAll('a');
console.log("Src before: " + $('#emptyImage').attr('src'));
// Iterate over all links
links.forEach((el) => {
// Get index of 'empty' in string if exists
if (el.search.indexOf('empty') !== -1) {
// Modify src to new src
$(el).find('img').attr("src", "newDir/newImageEmpty.jpg");
}
});
console.log("Src after: " + $('#emptyImage').attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="userShop">
<p class="shoppingbaskets">
<img id="emptyImage" src="image/empty.png" title="empty" width="50" height="50">
<img src="image/full.png" title="full" width="50" height="50">
<img src="image/semi.png" title="semi" width="50" height="50">
<img src="image/abandoned.png" title="abandoned" width="50" height="50">
<img src="image/completed.png" title="completed" width="50" height="50">
</p>
</div>

javascript function is executed only one time

I have a javascript function and I want to call it 12 times.
So I did like this:
Here I have 12 images:
<img id="img1" src=""> </img>
<img id="img2" src=""> </img>
<img id="img3" src=""> </img>
<img id="img4" src=""> </img>
<img id="img5" src=""> </img>
<img id="img6" src=""> </img>
<img id="img7" src=""> </img>
<img id="img8" src=""> </img>
<img id="img9" src=""> </img>
<img id="img10" src=""> </img>
<img id="img11" src=""> </img>
<img id="img12" src=""> </img>
Here the function is defined:
function addImageSource(id,another_variable) {
var imageSource = "http://..."+ another_variable + "test";
$("#img" + id).attr("src", imageSource);
}
And here I call it:
var itm_id = 1;
while(itm_id < 13){
addImageSource(item_id, "another_variable" );
itm_id++
}
Why is this function executed only one time? Can somebody tell me why?
You'll need to use a for loop so you'll want something like
for (var itm_id = 1; itm_id < 13; itm_id++){
addImageSource(itm_id, "another_variable" );
}
You need for instead of if:
for (var itm_id = 1 ; itm_id < 13; itm_id++) {
addImageSource(itm_id, "another_variable" );
}
also you made a mistake with this line:
addImageSource(item_id, "another_variable" );
it should be:
addImageSource(itm_id, "another_variable" );
You need to place the function call inside of a loop. Right now you are using a conditional which is a decision making construct, not a loop.
Replace:
var itm_id = 1;
if (itm_id < 13){
addImageSource(item_id, "another_variable" );
itm_id++
}
With a for loop like this:
for (var itm_id=1 ; itm_id < 13 ; itm_id++) {
addImageSource(itm_id, "another_variable" );
}

Method for randomly loading paired images

I've created a webpage with many (over 100) paired flash cards with Question (image) flipping to Answer (image) when clicked. If possible I would like to be able to randomise the order in which the question/answer pairs load with each page load/refresh.
<div class="content4Column gap">
<div class="card-container">
<div class="card click" data-direction="left">
<div class="front">
<img src="Intermolecular/Q1.png" width="100%" height="100%" alt="">
</div>
<div class="back">
<img src="Intermolecular/A1.png" width="100%" height="100%" alt="">
</div></div></div></div>
Try
var QAPairs = [];
var QATotal = 200; // total numbers of QA pairs
var QA = 20; //number of QA pairs you want. Set to QATotal to include all QA pairs
while(QAPairs.length != QA){
var rand = Math.floor(Math.random()*QATotal);
if(QAPairs.indexOf(rand) == -1){
QAPairs.push(rand);
// If you want to show them all at a time
document.getElementsByClassName("card click")[0].innerHTML = document.getElementsByClassName("card click")[0].innerHTML + '<div class="front">\
<img src="Intermolecular/Q' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>\
<div class="back">\
<img src="Intermolecular/A' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>';
}
}
// if you want to show them one at a time
var i = 0;
function updateCard(){
document.getElementsByClassName("card click")[0].innerHTML = '<div class="front">\
<img src="Intermolecular/Q' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>\
<div class="back">\
<img src="Intermolecular/A' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>';
i++;
}

Using sketch.js I want to download more of the produced data

When I press the download key on it does not download the quote that is present. Is there a way to change this? I tried playing around with the "data-" tag but can get nothing to work.
Here is the code
<title>SNUGGLETOOTH</title>
</head>
<body>
<nav>
<div id="SketchTools">
<!-- Basic tools -->
<img src="img/black_icon.png" alt="Black"/>
<img src="img/red_icon.png" alt="Red"/>
<img src="img/green_icon.png" alt="Green"/>
<img src="img/blue_icon.png" alt="Blue"/>
<img src="img/yellow_icon.png" alt="Yellow"/>
<img src="img/cyan_icon.png" alt="Cyan"/>
<!-- Advanced colors -->
<img src="img/alizarin_icon.png" alt="Alizarin"/>
<img src="img/pomegrante_icon.png" alt="Pomegrante"/>
<img src="img/emerald_icon.png" alt="Emerald"/>
<img src="img/torquoise_icon.png" alt="Torquoise"/>
<img src="img/peterriver_icon.png" alt="Peter River"/>
<img src="img/amethyst_icon.png" alt="Amethyst"/>
<img src="img/sunflower_icon.png" alt="Sun Flower"/>
<img src="img/orange_icon.png" alt="Orange"/>
<img src="img/clouds_icon.png" alt="Clouds"/>
<img src="img/silver_icon.png" alt="Silver"/>
<img src="img/asbestos_icon.png" alt="Asbestos"/>
<img src="img/wetasphalt_icon.png" alt="Wet Asphalt"/>
</br> <img src="img/eraser_icon.png" alt="Eraser"/>
<!-- Size options -->
<img src="img/pencil_icon.png" alt="Pencil"/>
<img src="img/pen_icon.png" alt="Pen"/>
<img src="img/stick_icon.png" alt="Stick"/>
<img src="img/smallbrush_icon.png" alt="Small brush"/>
<img src="img/mediumbrush_icon.png" alt="Medium brush"/>
<img src="img/bigbrush_icon.png" alt="Big brush"/>
<img src="img/bucket_icon.png" alt="Huge bucket"/>
Download
<br/>
</div>
<div class="links">
<ul>
<li><img src="ficon.png" alt="Facebook"></li>
<li><img src="igramicon.png" alt="Instagram"></li>
<li><img src="picon.png" alt="Pinterest"></li>
<li><img src="mcicon.png" alt="Mixcloud"></li>
<li><img src="twicon.png" alt="Twitter"></li>
</ul>
</div>
<div class="message">
<div data id="quote"></div>
<script>
(function() {
var quotes = [
{ text: "Snuggletooth likes pancakes"},
{ text: "Would you like Snuggletooth to tuck you in?"},
{ text: " Snuggletooth loves you"},
{ text: "Snuggletooth is here for you"},
{ text: "Did you know that Snuggletooth </br>can be in 2 places at once?"},
{ text: "Heyyyy!<br> I was just thinking about you </br>Love Snuggletooth" },
{ text: "Wanna Sandwich??</br>xSnuggletooth"},
{ text: "Want some breakfast???</br> ;) Snuggletooth"},
{ text: "Snuggletooth-a-riffic!!!"},
{ text: "Snuggletooth makes great popcorn!"},
{ text: "Come over to Snuggletooth's! He makes a great guacamole!"},
{ text: "Snuggletooth likes his bubblebaths to smell like bubblegum"},
{ text: "Snuggletooth wants to know what are you up to later?"},
{ text: "Snuggletooth-a-licious!!!"},
];
var quote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("quote").innerHTML =
'<p>' + quote.text + '</p>' +
'' + '';
})();
</script>
</div>
</nav>
<canvas id="SketchPad" width="1125" height="600">
</canvas>
</div>
<script type="text/javascript">
$(function() {
$('#SketchPad').sketch();
});
</script>
Try utilizing window.URL.createObjectURL , also adding style element to exported objectURL . See Drawing DOM objects into a canvas
$(function() {
$('#SketchPad').sketch();
$("#DownloadPng").on("click", function(e) {
e.preventDefault();
var canvas = document.getElementById('SketchPad');
var ctx = canvas.getContext('2d');
var style = $("style");
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="1125" height="600">'
+ '<foreignObject width="100%" height="100%">'
+ '<div xmlns="http://www.w3.org/1999/xhtml">'
+ $(".message")[0].outerHTML
+ '</div>'
+ '<style xmlns="http://www.w3.org/1999/xhtml">'
+ style[0].innerHTML + '</style>'
+ '</foreignObject>'
+ '</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
var popup = window.open(url, "popup")
})
});
jsfiddle http://jsfiddle.net/e1ovm9mn/1/

Categories