How to call function on keyup - Javascript - javascript

I am triying to create mathjax output to png file
I have created a JSFiddle here
I used code like below, I have an html code like
function myFunction(eqn){
window.MathJax = {
jax: ["input/TeX", "output/SVG"],
extensions: ["tex2jax.js", "MathMenu.js", "MathZoom.js"],
showMathMenu: false,
showProcessingMessages: false,
messageStyle: "none",
SVG: {
useGlobalCache: false
},
TeX: {
extensions: ["AMSmath.js", "AMSsymbols.js", "autoload-all.js"]
},
AuthorInit: function() {
MathJax.Hub.Register.StartupHook("End", function() {
var mj2img = function(texstring, callback) {
var input = texstring;
var wrapper = document.createElement("div");
wrapper.innerHTML = input;
var output = { svg: "", img: ""};
MathJax.Hub.Queue(["Typeset", MathJax.Hub, wrapper]);
MathJax.Hub.Queue(function() {
var mjOut = wrapper.getElementsByTagName("svg")[0];
mjOut.setAttribute("xmlns", "http://www.w3.org/2000/svg");
// thanks, https://spin.atomicobject.com/2014/01/21/convert-svg-to-png/
output.svg = mjOut.outerHTML;
var image = new Image();
image.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(output.svg)));
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
output.img = canvas.toDataURL('image/png');
callback(output);
};
});
}
mj2img(eqn, function(output){
const t = document.getElementById("target"); const i = document.createElement('img'); i.src = output.img; t.append(i);
});
});
}
};
}
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function() {
// remote script has loaded
};
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
<textarea onkeyup="myFunction(this.value)"></textarea>
<div id="target"></div>
How to display image when keyup a form containing textarea?
Here is a working version of above code by giving direct value.

standard pattern for keyup Event listener
document.getElementById("target").onkeyup = function() {funName()};
According to your specific problem. I'm not pretty sure where do you want to apply it

Related

Extension for Chrome script

Hello everyone i was creating a script for an extension for chrome, and i'm having problem with the format of this script. Do you know what is missing or wrong? Thanks.
The first one is the script that i have the proble yo upload on extension chrome setting which says (Manifest is not valid JSON. Line: 2, column: 18, Syntax error.)
`"permissions": [
"activeTab",
"tabs"
],
The second one is the script which contains the content.
"permissions": [
"activeTab",
"tabs"
],
This is the other script i have done it.
// content.js
var button = document.createElement("button");
button.innerHTML = "Take Screenshot";
button.onclick = function() {
chrome.tabs.captureVisibleTab(null, {}, function(img) {
chrome.tabs.create({url: img});
});
};
document.body.appendChild(button);
function addNote(img) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = img;
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
};
var input = document.createElement("input");
input.type = "text";
input.placeholder = "Enter note here";
input.oninput = function() {
ctx.font = "30px Arial";
ctx.fillText(input.value, 10, 50);
};
document.body.appendChild(input);
var saveBtn = document.createElement("button");
saveBtn.innerHTML = "Save";
saveBtn.onclick = function() {
var download = document.createElement("a");
download.href = canvas.toDataURL();
download.download = "annotated-screenshot.png";
download.click();
};
document.body.appendChild(saveBtn);
}

Video Js is not defined when call in external js file

(function () {
// Creating and Appending scripts dynamically
function createScript(src) {
var script = document.createElement('script');
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
// End script tags Here
function createLink(href) {
var link = document.createElement('link');
link.href = href;
link.rel = "stylesheet";
link.type = "type/css";
document.getElementsByTagName('head')[0].appendChild(link);
}
createLink('http://vjs.zencdn.net/4.12/video-js.css');
createScript('http://vjs.zencdn.net/4.12/video.js');
createLink('http://localhost/projects/test/bin/videojs.vast.vpaid.min.css');
createScript('http://localhost/projects/test/bin/videojs_4.vast.vpaid.min.js');
createScript('http://localhost/projects/test/bin/es5-shim.js');
createScript('http://localhost/projects/test/bin/ie8fix.js');
// DIV 2
// Div to hold the video
var divContainer = document.createElement('div');
divContainer.class = 'example-video-container';
divContainer.style.display = 'inline-block';
document.getElementById("video3438445[CB]").appendChild(divContainer);
// End parent Div here (parent of video div/tag)
// Video Player Below
// Create the video tag for html video player
var video = document.createElement('video');
video.id = 'video';
/*video.width = 300;
video.height = 250;*/
video.className = 'video-js vjs-default-skin';
video.autoplay = true;
video.controls = true;
video.muted = true;
video.preload = 'auto';
video.poster = "http://vjs.zencdn.net/v/oceans.png";
//video.data-setup = '{}';
// Function to create sources for video
function addSourceToVideo(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
addSourceToVideo(video, 'http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4', 'video/mp4');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/webm');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/ogg');
var paragraph = document.createElement('p');
paragraph.innerHTML = "Video PlayBack Not Supported";
video.appendChild(paragraph);
video.load();
//video.play();
divContainer.appendChild(video);
// Video player creation ends here
var vt = 'Vast_tag_url';
var vpaidPath = 'http://localhost/projects/test/bin/VPAIDFlash.swf';
setTimeout(myFunction, 1000);
function myFunction() {
var player = videojs(
"video", {
plugins: {
"vastClient": {
"adTagUrl": vt,
"adCancelTimeout": 15000,
"adsEnabled": true,
"playAdAlways": true,
"vpaidFlashLoaderPath": vpaidPath
}
}
})
}
})();
It works on normal HTML page when we have CSS and JS in head then a div with video and JS functions in body. But when I created a JS file and included it by javascript then it is not working.
Please suggest me what I am doing wrong.
Thanks so much for your response. My issue has been resolved. I used following code for this.
function loadScriptSync(src) {
var s = document.createElement('script');
s.src = src;
s.type = "text/javascript";
s.async = false; // <-- this is important
document.getElementsByTagName('head')[0].appendChild(s);
}
It will load js files synchronously.
The way you are loading the scripts is asynchronously.
You could either load them in the head directly, or implement a method that will listen to the loading events. Example below written in ES6.
function loadScript(src) {
return new Promise((onFulfilled, onRejected) => {
const script = document.createElement('script');
let loaded;
// set source path to load
script.setAttribute('src', src);
script.onreadystatechange = script.onload = () => {
if (!loaded) {
onFulfilled(script);
}
loaded = true;
};
script.onerror = function() {
// something went wrong
};
// append the given script
document.getElementsByTagName('head')[0].appendChild(script);
});
}
loadScript('http://url').then(() => {
// do something now that the script is loaded.
});
Now you will be sure that when the promise is fulfilled, the script is loaded successfully.

Esri Take Map Scrrenshots using Javascript

I am trying to generate a pdf report including current map screenshot of ESRI map using JavaScript. Here is my code.
var getCurrentMapScreenShot = function (success, error) {
esriLoader.Config.defaults.io.proxyUrl = myAppSettingsModel.SettingsModel.MapSettings.AGSProxyURL;
esriLoader.Config.defaults.io.alwaysUseProxy = true;
var printTask = new esriLoader.PrintTask("myexportUrl");
var template = new esriLoader.PrintTemplate();
template.exportOptions = {
width: 600,
height: 600,
dpi: 96
};
template.format = "image/png";
template.layout = "MAP_ONLY",
template.preserveScale = true;
template.layoutOptions = {
legendLayers: [], // empty array means no legend
scalebarUnit: "Miles"
};
var params = new esriLoader.PrintParameters();
params.map = map;
params.template = template;
printTask.execute(params, success, error);
}
This function will give you an event that contains a url , Then I am passing this url to get map base64 data.
Here is the function calling.
map.GetCurrentMapScreenShot(function (event) {
var mapScreenShotURL = event.url;
Factory.GetBase64ForImgUrl(mapScreenShotURL,
function (mapImageBase64Encoded) {});
and here is the function that converts url to base64image
function getBase64ForImgUrl(url, callback, outputFormat) {
console.log("#################### Summary Report Image " + url);
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
// Clean up
canvas = null;
};
img.src = url;
}
I am getting base64 image data of the map , But the problem is that, I am getting blurred image of the map with no feature layers and no icons..And also map contains some junk texts.
Thanks
I resolved the issue almost, Now I am getting the map image that contains map Icons and layer graphics, But unfortunately still getting some junk texts.
I have changed the code as follows.
template.format = "JPG";
template.layout = "A4 Landscape",
template.preserveScale = false;
template.layoutOptions = {
"legendLayers": [], // empty array means no legend
"scalebarUnit": "Miles"
}

Is there a way to access fonts icons from html5 canvas?

I am new to html5 canvas.
I need to display fonticons (fontawesome) as images.
Is this possible? Thanks
It is indeed possible, though it is a bit cumbersome.
Since Canvas will draw with a fallback font if the actual font it not yet ready, and since fonts are lazy loaded you will need to hold of rendering until the font is ready. This should be possible using something like Google/Typekit's Web Font Loader (https://github.com/typekit/webfontloader)
Once the font is ready, you can draw it in canvas as any other string, something like
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = '48px FontAwesome';
ctx.fillText(String.fromCharCode(61449), 10, 50);
The biggest challenge is that you have to remap all the symbols in Font Awesome, the their JavaScript char representations.
Edit:
This can actually be done using the name, by calcualting CSS rules
getFAChar = function (name) {
var elm = document.createElement('i');
elm.className = 'fa fa-' + name;
elm.style.display = 'none';
document.body.appendChild(elm);
var content = window.getComputedStyle(
elm, ':before'
).getPropertyValue('content')
document.body.removeChild(elm);
return content;
};
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = '48px FontAwesome';
ctx.fillText(getFAChar('bed'), 10, 50)
Edit:
To improve performance, FA icons should be cached, especially if the Canvas is redrawn often (adding and removing a lot of DOM elements is not a good idea when trying to reach 60 fps)
var FontAwesome = (function () {
var me = {},
FACache = {};
function find (name) {
var elm = document.createElement('i');
elm.className = 'fa fa-' + name;
elm.style.display = 'none';
document.body.appendChild(elm);
var content = window.getComputedStyle(
elm, ':before'
).getPropertyValue('content')
document.body.removeChild(elm);
return content;
};
me.get = function (name) {
if (!!FACache[name]) return FACache[name];
var c = find(name);
FACache[name] = c;
return c;
};
return me;
}());
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = '48px FontAwesome';
ctx.fillText(FontAwesome.get('bed'), 10, 50);
Edit
Complete example using deferred render, auto css injection and mapping of css chars, though only tested in Chrome (Uses font loading API and Promises without polyfill)
var FontAwesome = function () {
return new Promise(function (done, failed) {
var me = {},
FACache = {};
function find (name) {
var elm = document.createElement('i');
elm.className = 'fa fa-' + name;
elm.style.display = 'none';
document.body.appendChild(elm);
var content = window.getComputedStyle(
elm, ':before'
).getPropertyValue('content')
document.body.removeChild(elm);
return content;
};
me.get = function (name) {
if (!!FACache[name]) return FACache[name];
var c = find(name)[1];
FACache[name] = c;
return c;
};
(function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.onload = function () {
document.fonts.load('10px FontAwesome')
.then(function (e) { done(me); })
.catch(failed);
}
l.href = '//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
}());
});
};
FontAwesome()
.then(function (fa) {
// All set, and ready to render!
var ctx = document.getElementById('canvas').getContext('2d');
ctx.font = '48px FontAwesome';
ctx.fillText(fa.get('bed'), 10, 50);
});
<canvas id="canvas"></canvas>

WinJS Low Memory issue with ZXing

I am creating a Barcode scanner module for Windows 8 Metro App.
I some how success with my logic but suddenly I saw my application crash due to low memory issue.
<script>
var canvas = null;
var ctx = null;
var livePreview = null;
var count = 0,rescount=0;
function takepicture() {
var Capture = Windows.Media.Capture;
livePreview = document.getElementById("live-preview");
var mediaCapture = new Capture.MediaCapture();
canvas = document.getElementById("Vcanvas");
ctx=canvas.getContext('2d');
livePreview.addEventListener('play', function () { var i = window.setInterval(function () { ctx.drawImage(livePreview, 0, 0, canvas.width, canvas.height); scanCanvasEasy(); }, 20); }, false);
livePreview.addEventListener('pause', function () { window.clearInterval(i); }, false);
livePreview.addEventListener('ended', function () { clearInterval(i); }, false);
/*
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.videosLibrary;
openPicker.fileTypeFilter.replaceAll([".mp4", ".avi", ".ogg"]);
openPicker.pickSingleFileAsync()
.then(function (file) {
if (file) {
// draw the image
var img = new Image;
//img.onload = function () {
// canvas.width = img.width;
// canvas.height = img.height;
// ctx.drawImage(img, 0, 0, img.width, img.height);
// scanCanvasEasy();
//}
//img.src = URL.createObjectURL(file);
// open a stream from the image
livePreview.src = URL.createObjectURL(file);
livePreview.play();
}
})*/
mediaCapture.initializeAsync().then(function () {
livePreview.src = URL.createObjectURL(mediaCapture);
livePreview.play();
});
}
function scanCanvasEasy() {
var imgd = ctx.getImageData(0, 0,canvas.width,canvas.height);
var pix = imgd.data;
var reader = new ZXing.BarcodeReader();
reader.onresultpointfound = function (resultPoint) {
// do something with the resultpoint location
console.log(resultPoint.toString());
}
// try to decode the raw pixel data
var result = reader.decode(pix, canvas.width, canvas.height, ZXing.BitmapFormat.rgba32);
/*
The above line cause that memory issue, without that line there is no change in memory level.
*/
// show the result
if (result) {
document.getElementById("result").innerText ="Result(+"+rescount++ +")==>"+ result.text;
}
else {
document.getElementById("error").innerText = "no barcode found" + count++;
}
}
</script>
I posted the whole code i used here I Just called the takepicture() method from button click event.
var result = reader.decode(pix, canvas.width, canvas.height, ZXing.BitmapFormat.rgba32);
This line cause memory issue.
Thanks in advance.
var reader = new ZXing.BarcodeReader();
Multiple instance of reader cause this issue. Just created one instance of reader and use it for all subsequent scan will fixed that issue.

Categories

Resources