Why does my file-preview not show my file the first time? - javascript

I want to read the picture from user's local file. (the user is under ie7 -ie9, so it doesn't support fully version of html5) I find the first time I assume the input|file value, the picture doesn't show, the second time I change another picture, the image can show. Just want to know how to make the first time I input picture it is can show.
I want read the picture from user's local file, I apply below code:
function ShowImage(obj){
var allowSuffix=".jpg|.gif|.bmp|.png"; //.jpg,.bmp,.gif,.png
var suffix=obj.value.substring(obj.value.lastIndexOf(".")+1).toLowerCase();
var browserVersion= window.navigator.userAgent.toUpperCase();
if(allowSuffix.indexOf(suffix)>-1){
if(browserVersion.indexOf("MSIE 7.0")>-1 || browserVersion.indexOf("MSIE 8.0")>-1 || browserVersion.indexOf("MSIE 9.0")>-1){//ie7, ie8, ie9
obj.select();
var source=document.selection.createRange().text;
obj.blur();
var newPreview = document.getElementById("divNewPreview");
newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = source;
newPreview.style.width = 160;
newPreview.style.height = 170;
newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").sizingMethod = 'scale';
$("#divPreview").attr("style","display:none");
$("#divNewPreview").attr("style","filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);width:160px;height:170px;border:solid 1px #d2e2e2;");
}
}
}
the html part code is easy like:
<div id="divNewPreview" style="filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image ); width: 160px; height: 170px; border: solid 1px #d2e2e2; display: none;"></div>
<p>
input file: <input type="file" onchange="ShowImage(this)" />
</p>

Older browsers have no access to the local filesystem. You need to post it to the server before you can view the file.

Related

Downloading a qrcode.js-generated QR code

I've searched the web countless times trying to find a way to solve this but I've come up empty-handed every time. I have been using qrcode.js to generate QR codes for a website, but I haven't figured out how to download the image once it's been generated. The code I use to generate the QR code looks like this:
var myQR = new QRCode(document.getElementById("qrcode"), {
text: "Made with QR Generator",
width: 128,
height: 128,
colorDark : qrdarkcolor,
colorLight : qrlightcolor,
correctLevel : QRCode.CorrectLevel.H
});
myQR.makeCode(qrdata);
I am trying to find a way to either download the QR code within the div or find the source and create a button that users can click on to download the image. I apologize if this is a commonly asked question, but I've searched many other questions that are similar to this and haven't found a clear answer. I would prefer to keep this site with only HTML, CSS, and Javascript if possible.
Thanks!
The image is generated through the plugin and takes a moment to render, so the method needs to be done with setTimeout. After that, we grab the src of the image and apply it to a download link (a link that has the attribute download in it)
Note this won't work in the snippet sandbox, but it's been tested on a normal web page and works great.
const makeQR = (url, filename) => {
var qrcode = new QRCode("qrcode", {
text: "http://jindo.dev.naver.com/collie",
width: 128,
height: 128,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
qrcode.makeCode(url);
setTimeout(() => {
let qelem = document.querySelector('#qrcode img')
let dlink = document.querySelector('#qrdl')
let qr = qelem.getAttribute('src');
dlink.setAttribute('href', qr);
dlink.setAttribute('download', 'filename');
dlink.removeAttribute('hidden');
}, 500);
}
makeQR(document.querySelector('#text').value, 'qr-code.png')
#qrcode {
width: 160px;
height: 160px;
margin-top: 15px;
}
<script src="https://cdn.jsdelivr.net/npm/davidshimjs-qrcodejs#0.0.2/qrcode.min.js"></script>
<input id="text" type="text" value="https://stackoverflow.com" style="width:80%" /><br />
<div id="qrcode"></div>
<a id='qrdl' hidden>Download</a>
You can use Qurious to generate QR code in canvas and then download it. Qurious has also its own padding option (it makes white borders around the qr code so it's possible to scan it after download).
Add this at the <head> part:
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
Html body:
<canvas id="qrcode"></canvas>
Script:
const makeQR = (your_data) => {
let qrcodeContainer = document.getElementById("qrcode");
qrcodeContainer.innerHTML = "";
new QRious({
element: qrcodeContainer,
value: your_data,
size: 600,
padding:50,
}); // generate QR code in canvas
downloadQR(); // function to download the image
}
function downloadQR() {
var link = document.createElement('a');
link.download = 'filename.png';
link.href = document.getElementById('qrcode').toDataURL()
link.click();
}
makeQR("Your value")
I noticed that the 'qrcodejs' is returning img with blank src on mobile device browsers(Android -> Chrome), whereas it returns an img with valid src (data URI) when you request from mobile as a 'desktop agent'.
You could able to test it by debugging the mobile.

Calculating path length of test [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to solve a problem where i need to know the length of the path of the text typed by the user. Example a user Types "Hello World" i need to check what will be the length of the path of Hello world when typed in a certain font with a certain font size(in pt).
The length that i will get i need to convert it into meters to i can use it in real world to build the Neon.
How should i approach the problem are there any libraries that can help me do this?
Thanks
I don't have any specific libraries to recommend, but here is a snippet of how you might go about doing what you want. The conversion from pixels to centimeters is approximate here, it's just a demo after all.
const getRuler = element => {
const ctx = document.createElement('canvas').getContext('2d');
const style = window.getComputedStyle(element);
const fontSize = style.getPropertyValue('font-size');
const fontFamily = style.getPropertyValue('font-family');
ctx.font = `${fontSize} ${fontFamily}`;
return ctx;
}
const element = document.querySelector('#my-element-with-text');
function updateLength(e) {
const element = e.target
const text = element.innerText;
const ruler = getRuler(element);
const length = ruler.measureText(text).width;
const result = document.querySelector('#length');
result.innerText = (length * 0.026458).toFixed(4) + ' centimeters';
}
element.addEventListener('keyup', updateLength);
body {
height: 100%;
width: 100%;
margin: 0;
}
main {
margin-top: 15vh;
margin-left: 10vw;
width: 85%;
}
#my-element-with-text {
border: 1px solid black;
border-radius: 3px;
height: 2em;
font-size: 5vw;
width: fit-content;
min-width: 200px;
line-height: 2em;
padding: 0 12px;
font-family: 'Helvetica Neue', sans-serif;
}
<main>
<div>Enter text here</div>
<div id='my-element-with-text' contenteditable='true'></div>
<div id='length'></div>
</main>
This is a multistep process, and for now I don't have all the answers.
Load the font to use as a webfont. Normally, this means you go to a provider like Google fonts and get a link to a stylesheet that will do the work for you, including deciding which font format your browser will understand. But in this case, you need the full address of the final font file. If you provide the font file on your own server, this would be trivial.
Since you ultimately need the file content itself, the best strategy is probably to load the font file via an AJAX request and then both insert it into the document font resources and to load it also into a special parser that gives access to the font outline data. This could be opentype.js - note it is a major piece of software with 162kB minified. As soon as the font is loaded, you can start to look for the text you want to measure:
window.fetch(fontUrl).then(response => {
// read response into an ArrayBuffer
return response.arrayBuffer();
}).then(buffer => {
// load into parser
const parsedFont = opentype.parse(buffer);
// load into browser resources, family is the name for CSS reference
const fontFace = new FontFace(family, buffer);
document.fonts.add(fontFace);
// add an event listener to your text input
document.querySelector('#textToMeasure').addEventListener('change', event => {
textToOutline(parsedFont, event.target.value);
});
});
Each time the text input changes, you now render that text to an SVG path. For that, you need to have an (invisible) SVG snippet in your page:
<svg width="0px" height="0px"><path id="outlinePath" d="" /></svg>
You get the path data by providing the text and the font size to the font object and then set them for your SVG <path>:
function textToOutline (font, text) {
// size means font size in pixels
const pathData = font.getPath(text, 0, 0, size).toPathData(4);
// write to path
const path = document.querySelector('#outlinePath');
path.setAttribute('d', pathData);
measureOutline(path);
}
Now the text outline is in a format that the browser can measure with its own API.
function measureOutline (path) {
// length in pixels
const pathLength = path.getTotalLength();
// factor would be the conversion factor to your intended unit,
// and unit the unit name
document.querySelector('#lengthResult').innerText = (pathLength * factor) + unit;
}

How to scroll the transcrib of a video in real time in html5

I would like to create a javascript html5 script that allows to have
poster and play a youtube video with its transcript.
and in this script I'd like a button that captures the images from the video as soon as I press the button.
And that the transcript is written in the browser and as the video progresses.
the goal is that at the end of the video I'll have a full article of the video.
Example:
1) I put a youtube link in the script
2) I see in the html5 page the video
3) I press play on the video
4) the transcription how to write in the html page ok
5) at any time I can make a pose of the video to take a screenshot of the image.
the result must be the following.
I'm taking a screenshot so one frame of the video to start with.
I've got the text underneath.
screenshot image
transcribed text
screenshot image
transcribed text
screenshot image
transcribed text
screenshot image
transcribed text
until the end of the video
the screenshot captures it's me who makes them by pressing the button to capture the screenshot.
I managed to make a page that takes the screenshot with a button from a local mp4 video.
but what I can't do, and that's where I need your help:
1) is to play a youtube video in an html5 page with always the screen shot button
2) write in real time the transcription in a html5 page until the end of the video.
thank you for your help.
<script>
var videoId = 'video';
var scaleFactor = 0.5;
var snapshots = [] ;
/**
* Captures a image frame from the provided video element.
*
* #param {Video} video HTML5 video element from where the image frame will be captured.
* #param {Number} scaleFactor Factor to scale the canvas element that will be return. This is an optional parameter.
*
* #return {Canvas}
*/
function capture(video, scaleFactor) {
if (scaleFactor == null) {
scaleFactor = 1;
}
var w = video.videoWidth * scaleFactor;
var h = video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
innerHTML = "<br>";
return canvas ;
}
/**
* Invokes the <code>capture</code> function and attaches the canvas element to the DOM.
*/
function shoot() {
var video = document.getElementById(videoId);
var output = document.getElementById('output');
var canvas = capture(video, scaleFactor);
canvas.onclick = function() {
window.open(this.toDataURL(image/jpg));
};
snapshots.unshift(canvas);
output.innerHTML = '';
for (var i = 0; i < 10; i++) {
output.appendChild(snapshots[i]) ;
}
}
(function() {
var captureit = document.getElementById('cit');
captureit.click();
})();
</script>
<style>
.wrap {
border: solid 1px #ccc;
padding: 10px;
text-align: center;
}
#output {
display: inline-block;
top: 4px;
position: relative;
border: dotted 1px #ccc;
padding: 2px;
}
.button {
border: solid 2px #ccc;
}
</style>
<html>
<body>
<div class="wrap">
<video id="video" width="600" controls="true">
<source src = "http://127.0.0.1/divi.mp4" type = "video/mp4"></source>
<!-- FireFox 3.5 -->
<source src = "http://127.0.0.1/divi.mp4" type = "video/mp4"></source>
<!-- WebKit -->
Your browser does not support HTML5 video tag. Please download FireFox 3.5 or higher.
</video>
<br/>
<button id="cit" onclick="shoot()" class="button">Capture</button>
<br/>
<div id="output">
</div>
here are two scripts the first one has a button that captures the images of an MP4 video
and the second one that stupidly extracts all the images from a video automatically...
what I'm missing is:
1) put the link of any youtube video that is displayed in the html5 page
2) when I click on play I get the transcript which is written below the video automatically.
3) I want to do a pose to make a screen capture
4) continue transcription
5) image capture of the video etc...
text
image
text
image
until the end of the video
the goal of getting my full article.
I have a lot of tutorials on youtube and I would like to have them in documentation on my website.
create a complete article for each video
the best thing is to have a motion capture of the automatic image.
that is to say:
1) I click on the video
2) the script takes a first capture of the video
3) the transcription is written below the image captured in the html5 page
4) as soon as the image changes the script detects it and takes the print screen by itself without any button.
and so on until the end of the video without my intervention.
it creates a complete article on its own
just by putting my youtube link!!
It'll be the best of the best...
thank you for your support I'm sure that among you there are people who have websites and would like to have a script that can do articles alone...
3) as soon as

how to export SVG graph to pdf

I am using a API which render the line graph in SVG but I am not able to export it into PDF like other graph which render in HTML5 canvas
$(function() {
// let's loop to build tooltips and x labels.
var thelabels = new Array(30);
for (var i = 0; i < 30; i++) {
thelabels[i] = (i % 6 === 0) ? (i + 1) + " september" : "";
}
// build the chart using the "google analytics" template.
$("#chart").chart({
template: "raphael_analytics",
labels: thelabels,
values: values()
});
// start a loop that sets new data in the chart every 5 seconds.
});
Code is available in jsfiddle
while searching I got a link where I can export SVG graph to PDF but the demo what they provided it is not working and they used Perl script to export.
I wanted to export from client/browser to canvas image data
Edited
I have seen one more library in github it allows you to download SVG to PDF from client side. But in the library they have used a object called "RGBColor(fillColor)" this throw an error like RGBColor is not defined so is there any library I need to include..???
I had to convert graphs and pie charts to pdf and wound up using this third party package. It converts HTML to PDF. Just render graph and then pass the URL to the converter. It worked great. Its called HiQPDf
Perhaps you can
print your webpage to PDF.
convert it using any script like svgToPdf.js.
To print as PDF, define a stylesheet for printing
#media print {
body * { visibility: hidden; }
#chart * { visibility: visible; }
#chart { position: absolute; top: 10px; left: 10px; }
}
and call print using javascript
var chart = document.getElementById('chart').innerHTML,
body = document.body.innerHTML;
document.body.innerHTML = chart;
window.print();
document.body.innerHTML = body;
This is not local but works fine. Using http://www.cloudformatter.com/css2pdf to render your chart. I added their javascript and a button to download the PDF.
http://jsfiddle.net/JehdF/1237/
<button onclick="return xepOnline.Formatter.Format('chart',{pageWidth:'11in', pageHeight:'8.5in',render:'download'});">Get PDF</button>
<div id="chart" style="width: 100%; height: 600px"></div>
Use instructions are here: http://www.cloudformatter.com/CSS2Pdf.APIDoc.Usage
Result:

Browse Image and Insert into Iframe

I was wondering if this is possible.
I want to create a function to retrieve an image and insert into an iframe. The user must be able to choose a file (image/video) and it will be inserted into an iframe.
main.html
<input type="file" id="addImage"> I have used this for the user to choose a file.
<iframe class="frame" id="frame" src="insert.html"></iframe> And this for the iframe. The iframe src is another html document.
insert.html
<span id="edit"></span> is within the insert.html where the image needs to be inserted to.
I don't quite understand how javascript can be used to retrieve the image from the users selection and insert into the iframe.
Is this possible?
Yes, here is an example. The key is to hook onto the iframe and then use its contentWindow.
EDIT
Additionally, I don't know if you meant the browse for file or the drag'n'drop API so I implemented both.
Lots of help from these sources:
file-api : How to interact with the file-api
drag-drop events : Events to key off of when dragging and dropping
And here is a fiddle:
JSFiddle
CSS
*{
font-family: Arial;
}
.section{
width: 400px;
padding: 20px;
margin: auto;
}
#dragDiv{
background-color: #ffffcc;
}
#browseDiv{
background-color: #ccffcc;
}
#iframeDiv{
background-color: #ffcccc;
}
#dropTarget{
width: 300px;
height: 300px;
border-style: dashed;
border-width: 5px;
}
.dropEnabled{
border-color: #999999;
}
.dropEnabled:hover{
border-color: #ff9933;
}
.dropMe{
border-color: #99ff99;
}
JS
/**
* I set up the listeners for dragging and dropping as well
* as creating an iFrame for holding dragged in images
* #returns {undefined}
*/
function main() {
// The div that receives drops and the new iFrame
var targetDiv = document.getElementById("dropTarget"),
iframe = document.createElement("iframe");
// Set the iframe to a blank page
iframe.src = "about:blank";
// Append it to the target
document.getElementById("iframeTarget").appendChild(iframe);
// Drag over is when an object is hovering over the div
// e.preventDefault keeps the page from changing
targetDiv.addEventListener("dragover", function(e) {
e.preventDefault();
this.className = "dropMe";
}, false);
// Drag leave is when the object leaves the div but isn't dropped
targetDiv.addEventListener("dragleave", function(e) {
e.preventDefault();
this.className = "dropEnabled";
}, false);
// Drop is when the click is released
targetDiv.addEventListener("drop", function(e) {
e.preventDefault();
this.className = "dropEnabled";
loadFile(e.dataTransfer.files[0], iframe);
}, false);
document.getElementById("upload").addEventListener("click", function() {
var file = document.getElementById("browsedFile").files[0];
loadFile(file, iframe);
}, false);
}
/**
* Load a file and then put it on an ifrmae
* #param {Element} f The file that needs to get loaded
* #param {Element} destination The iframe that the file is appended to
* #returns {undefined}
*/
function loadFile(f, destination) {
// Make a file reader to interpret the file
var reader = new FileReader();
// When the reader is done reading,
// Make a new image tag and append it to the iFrame
reader.onload = function(event) {
var newImage = document.createElement("img");
newImage.src = event.target.result;
destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newImage);
};
// Tell the reader to start reading asynchrounously
reader.readAsDataURL(f);
}
// Run the main script
window.onload = main;
HTML
<!DOCTYPE html>
<html>
<head>
<title>I framed it</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="dragDiv" class="section">
<div>The div below receives dragged in files</div>
<div id="dropTarget" class="dropEnabled"></div>
</div>
<div id="browseDiv" class="section">
<div>I upload stuff the boring way</div>
<input type="file" id="browsedFile"><button id="upload">Upload</button>
</div>
<div id="iframeDiv" class="section">
<div>And below me, an iFrame gets created</div>
<div id="iframeTarget"></div>
</div>
</body>
</html>
And here is the result:
And the DOM:
EDIT
A comment was made about how to do this with videos as well. There are several ways to do it, but here is one way that I would do it using the HTML5 <vido> tag which you can find more information on here: HTML Videos.
One tricky thing that I'm sure is rather cludgy is how to say what kind of file you should be loading. I use a switch() on the file's type attribute which usually evaluates to something like: image/png or video/mp4 for MP4 videos. However, this ties you to a specific file format. A better way to do it would be to make a regular expression that figures out if it's just an image or a video and ignore the format since the process is rougly the same for all files of those types.
I added my own regular expression implementation. Probably, not the best, but it allows all appropriate image types to come through now.
Also, I tried using some sample videos from Apple which can be found here: Sample QuickTime Movies. However, those did not work for some reason. So after that, I just downloaded the sample videos that W3Schools uses in their tutorial. I'm telling you this so that in case you try it and it doesn't work, it might be the file itself and not your code.
Edited loadFile() Function
/**
* Load a file and then put it on an ifrmae
* #param {Element} f The file that needs to get loaded
* #param {Element} destination The iframe that the file is appended to
* #returns {undefined}
*/
function loadFile(f, destination) {
// Make a file reader to interpret the file
var reader = new FileReader(),
loaderFunc = null,
typeRegEx = /^(\w+)\//,
contentType = f.type.match(typeRegEx)[1];
// Figure out how to load the data
switch (contentType) {
case "video":
loaderFunc = function(event) {
var newVideo = document.createElement("video"),
newVideoSource = document.createElement("source");
newVideo.width = 300;
newVideo.height = 300;
newVideo.setAttribute("controls");
newVideoSource.src = event.target.result;
newVideoSource.type = f.type;
destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newVideo);
newVideo.appendChild(newVideoSource);
};
break;
case "image":
loaderFunc = function(event) {
var newImage = document.createElement("img");
newImage.src = event.target.result;
destination.contentWindow.document.getElementsByTagName("body")[0].appendChild(newImage);
};
break;
default:
console.log("Unknown file type");
return;
}
// We should have returned, but just make sure
if (loaderFunc) {
// When the reader is done reading,
// Make a new image tag and append it to the iFrame
reader.onload = loaderFunc;
// Tell the reader to start reading asynchrounously
reader.readAsDataURL(f);
}
}
You can manipulate directly an iframe from an other if they are from same domain.
See jQuery/JavaScript: accessing contents of an iframe
What you can do if this is not the case is :
Setting up a communication process between both pages (see How to communicate between iframe and the parent site?)
or
Uploading your file to a server, and refresh the "insert.html" page to display the uploaded image.

Categories

Resources