Paste image from clipboard to html page - javascript

I'm learning angular and I'm trying to use copy image from clipboard and paste it in html web page.
I found a solution in Javascript that i want to convert to typeScript. But it doesn't work when I test it. It works fine on jsfiddle : http://jsfiddle.net/KJW4E/1739/
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
var CLIPBOARD = new CLIPBOARD_CLASS("my_canvas", true);
/**
* image pasting into canvas
*
* #param {string} canvas_id - canvas id
* #param {boolean} autoresize - if canvas will be resized
*/
function CLIPBOARD_CLASS(canvas_id, autoresize) {
var _self = this;
var canvas = document.getElementById(canvas_id);
var ctx = document.getElementById(canvas_id).getContext("2d");
var ctrl_pressed = false;
var command_pressed = false;
var paste_event_support;
var pasteCatcher;
//handlers
document.addEventListener('keydown', function (e) {
_self.on_keyboard_action(e);
}, false); //firefox fix
document.addEventListener('keyup', function (e) {
_self.on_keyboardup_action(e);
}, false); //firefox fix
document.addEventListener('paste', function (e) {
_self.paste_auto(e);
}, false); //official paste handler
//constructor - we ignore security checks here
this.init = function () {
pasteCatcher = document.createElement("div");
pasteCatcher.setAttribute("id", "paste_ff");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;width:10px;margin-left:-20px;';
document.body.appendChild(pasteCatcher);
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (paste_event_support === true || ctrl_pressed == false || mutation.type != 'childList'){
//we already got data in paste_auto()
return true;
}
//if paste handle failed - capture pasted object manually
if(mutation.addedNodes.length == 1) {
if (mutation.addedNodes[0].src != undefined) {
//image
_self.paste_createImage(mutation.addedNodes[0].src);
}
//register cleanup after some time.
setTimeout(function () {
pasteCatcher.innerHTML = '';
}, 20);
}
});
});
var target = document.getElementById('paste_ff');
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);
}();
//default paste action
this.paste_auto = function (e) {
paste_event_support = false;
if(pasteCatcher != undefined){
pasteCatcher.innerHTML = '';
}
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
paste_event_support = true;
//access data directly
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
//image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
this.paste_createImage(source);
}
}
e.preventDefault();
}
else {
//wait for DOMSubtreeModified event
//https://bugzilla.mozilla.org/show_bug.cgi?id=891247
}
}
};
//on keyboard press
this.on_keyboard_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey) {
if (ctrl_pressed == false)
ctrl_pressed = true;
}
//v
if (k == 86) {
if (document.activeElement != undefined && document.activeElement.type == 'text') {
//let user paste into some input
return false;
}
if (ctrl_pressed == true && pasteCatcher != undefined){
pasteCatcher.focus();
}
}
};
//on kaybord release
this.on_keyboardup_action = function (event) {
//ctrl
if (event.ctrlKey == false && ctrl_pressed == true) {
ctrl_pressed = false;
}
//command
else if(event.metaKey == false && command_pressed == true){
command_pressed = false;
ctrl_pressed = false;
}
};
//draw pasted image to canvas
this.paste_createImage = function (source) {
var pastedImage = new Image();
pastedImage.onload = function () {
if(autoresize == true){
//resize
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
}
else{
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage.src = source;
};
}
</script>
</head>
<body>
1. Copy image data into clipboard or press Print Screen <br>
2. Press Ctrl+V (page/iframe must be focused):
<br /><br />
<button onclick="alert('Hello! I am an alert box!!');"></button>
<canvas style="border:1px solid grey;" id="my_canvas" width="300" height="300"></canvas>
</body>
</html>
I am using google chrome Version 70.0.3538.77
Thanks in advance

From the comments above, it sounds like you were trying to execute your bindings in the constructor of your component instead of within ngOnInit. This is a classic gotcha as the constructor spins up well before (in most cases) before the content on screen is finished rendering. ngOnInit is called as the component finalises its instantiation process.
https://angular-6ckpxd.stackblitz.io
The errors you receive are because typescript is strongly typed where javascript is not. You are pasting javascript code in (which is fine in most cases) but will need some casting to any if you want to eradicate most of them.

Related

Avoid DevTools menu

I have a code to avoid users opening devtools menu, the code works perfectly for me! But sometimes, when you watch a simple video at my website and put it on fullscreen, the script below returns false positive.
// chrome
var element = new Image;
var devtoolsOpen = false;
element.__defineGetter__("id", function() {
devtoolsOpen = true; // This only executes when devtools is open.
});
setInterval(function() {
devtoolsOpen = false;
//console.log(element);
if (devtoolsOpen && devtoolsOpen == true) {
window.location = "https://mywebsite.com/denied/";
}
}, 1000);
// all
var _interval = 200;
(function() {
'use strict';
var devtools = {
open: false,
orientation: null
};
var threshold = 160;
var emitEvent = function(state, orientation) {
window.dispatchEvent(new CustomEvent('devtoolschange', {
detail: {
open: state,
orientation: orientation
}
}));
};
setInterval(function() {
var widthThreshold = window.outerWidth - window.innerWidth > threshold;
var heightThreshold = window.outerHeight - window.innerHeight > threshold;
var orientation = widthThreshold ? 'vertical' : 'horizontal';
if (!(heightThreshold && widthThreshold) &&
((window.Firebug && window.Firebug.chrome && window.Firebug.chrome.isInitialized) || widthThreshold || heightThreshold)) {
if (!devtools.open || devtools.orientation !== orientation) {
emitEvent(true, orientation);
}
devtools.open = true;
devtools.orientation = orientation;
} else {
if (devtools.open) {
emitEvent(false, null);
}
devtools.open = false;
devtools.orientation = null;
}
}, _interval);
if (typeof module !== 'undefined' && module.exports) {
module.exports = devtools;
} else {
window.devtools = devtools;
}
setTimeout(function() {
_interval = 500;
}, 1000);
})();
// check if it's open
//console.log('is DevTools open?', window.devtools.open);
if (window.devtools.open && window.devtools.open == true) {
window.location = "https://mywebsite.com/denied/";
}
// get notified when it's opened/closed or orientation changes
window.addEventListener('devtoolschange', function(e) {
//console.log('is DevTools open?', e.detail.open);
if (e.detail.open && e.detail.open == true) {
window.location = "https://mywebsite.com/denied/";
}
});
// clear
console.API;
if (typeof console._commandLineAPI !== 'undefined') {
console.API = console._commandLineAPI; //chrome
} else if (typeof console._inspectorCommandLineAPI !== 'undefined') {
console.API = console._inspectorCommandLineAPI; //Safari
} else if (typeof console.clear !== 'undefined') {
console.API = console;
}
console.API.clear();
I reviewed the code many times and I wasn't able to find why this is happening. Do you have any idea about how can I solve it?
Thank you.

Autoplay Background HTML5 Sound/Video on Android and iOS

I digg deep into StackOwerflow but not get proper answer from any post.
First here is my code:
(function(a,n){
window.onload = function() {
var b = document.body,
userAgent = navigator.userAgent || navigator.vendor || window.opera,
playSound = function(file) {
var mediaAudio = new Audio(file);
mediaAudio.play();
};
if(b.id == 'fail' || b.id == 'success')
{
if ((/android/gi.test(userAgent) && !window.MSStream))
{
var vm = document.createElement("video"), type;
vm.autoPlay = false;
vm.controls = true;
vm.preload = 'auto';
vm.loop = false;
vm.muted = true;
vm.style.position = 'absolute';
vm.style.top = '-9999%';
vm.style.left = '-9999%';
vm.style.zIndex = '-1';
vm.id = 'video';
if(b.id == 'fail')
type = a;
else
type = n;
for(key in type)
{
if(/video/gi.test(key) && vm.canPlayType(key) == 'probably') {
vm.type = key;
vm.src = type[key];
b.appendChild(vm);
setTimeout(function(){
vm.muted = false;
vm.play();
},100);
return;
}
}
}
else
{
var au = new Audio(),type;
if(b.id == 'fail')
type = a;
else
type = n;
for(key in type)
{
if(/audio/gi.test(key) && au.canPlayType(key) == "probably") {
playSound(type[key]);
return;
}
}
}
}
}
}({
'audio/mpeg':'./sfx/not_ok.mp3',
'audio/wav':'./sfx/not_ok.wav',
'audio/ogg':'./sfx/not_ok.ogg',
'video/mp4; codecs=avc1.42E01E,mp4a.40.2':'./sfx/not_ok.mp4',
},
{
'audio/mpeg':'./sfx/ok.mp3',
'audio/wav':'./sfx/ok.wav',
'audio/ogg':'./sfx/ok.ogg',
'video/mp4; codecs=avc1.42E01E,mp4a.40.2':'./sfx/ok.mp4',
}));
I'm trying to play background sound on all devices on one special page. That page play fail or success sound.
All works great on desktop browsers but when I try to play on mobile, I not get results. In that code you see above, I add one hack where I on android platform generate hidden video and trying to autoplay but not have success.
Is there a way how I can trigger play for video or audio automaticaly?
Is there a way to emulate some click event on body to automaticaly play sound on click event or some other solution?
Thanks!

How i can use FileSaver.js module without Node.Js?

i have visited a github code to increase effort for saving a file from javascript/html. We have some problem with to use it, because it mae for node.js. I'v found some demo.js code to save the file from demo.html itself. But, it is useless because i unfortunatly can't edit, because i wonder it just for demo.html class, and it will become crash if i make a reference to another html file.
This is the code File Saver.js
/* FileSaver.js * A saveAs() FileSaver implementation. * 1.3.2 * 2016-06-16 18:25:19 * * By Eli Grey, http://eligrey.com * License: MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */
/*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! #source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js
*/
var saveAs = saveAs || (function(view) { "use strict"; // IE <10 is explicitly unsupported if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var
doc = view.document
// only get URL when necessary in case Blob.js hasn't overridden it yet , get_URL = function() { return view.URL || view.webkitURL || view; } , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = "download" in save_link , click = function(node) { var event = new MouseEvent("click"); node.dispatchEvent(event); } , is_safari = /constructor/i.test(view.HTMLElement) || view.safari , is_chrome_ios
=/CriOS\/[\d]+/.test(navigator.userAgent) , throw_outside = function(ex) { (view.setImmediate || view.setTimeout)(function() {
throw ex; }, 0); } , force_saveable_type = "application/octet-stream" // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to , arbitrary_revoke_timeout = 1000 * 40 // in ms , revoke = function(file) { var revoker = function() {
if (typeof file === "string") { // file is an object URL
get_URL().revokeObjectURL(file);
} else { // file is a File
file.remove();
} }; setTimeout(revoker, arbitrary_revoke_timeout); } , dispatch = function(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
} } } , auto_bom = function(blob) { // prepend BOM for UTF-8 XML and text/* types (including HTML) // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type}); } return blob; } , FileSaver = function(blob, name, no_auto_bom) { if (!no_auto_bom) {
blob = auto_bom(blob); } // First try a.download, then web filesystem, then object URLs var
filesaver = this
, type = blob.type
, force = type === force_saveable_type
, object_url
, dispatch_all = function() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function() {
if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function() {
var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
var popup = view.open(url, '_blank');
if(!popup) view.location.href = url;
url=undefined; // release reference before dispatching
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (!object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (force) {
view.location.href = object_url;
} else {
var opened = view.open(object_url, "_blank");
if (!opened) {
// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
} ; filesaver.readyState = filesaver.INIT;
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
setTimeout(function() {
save_link.href = object_url;
save_link.download = name;
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return; }
fs_error(); } , FS_proto = FileSaver.prototype , saveAs = function(blob, name, no_auto_bom) { return new FileSaver(blob, name || blob.name || "download", no_auto_bom); } ; // IE 10+ (native saveAs) if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { return function(blob, name, no_auto_bom) { name = name || blob.name || "download";
if (!no_auto_bom) {
blob = auto_bom(blob); } return navigator.msSaveOrOpenBlob(blob, name); }; }
FS_proto.abort = function(){}; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2;
FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
return saveAs; }(
typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content )); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) { module.exports.saveAs = saveAs; } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) { define("FileSaver.js", function() {
return saveAs; }); }
And the demo.js
/*! FileSaver.js demo script
* 2016-05-26
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See LICENSE.md
*/
/*! #source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
/*jshint laxbreak: true, laxcomma: true, smarttabs: true*/
/*global saveAs, self*/
(function(view) {
"use strict";
// The canvas drawing portion of the demo is based off the demo at
// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
var
document = view.document
, $ = function(id) {
return document.getElementById(id);
}
, session = view.sessionStorage
// only get URL when necessary in case Blob.js hasn't defined it yet
, get_blob = function() {
return view.Blob;
}
, canvas = $("canvas")
, canvas_options_form = $("canvas-options")
, canvas_filename = $("canvas-filename")
, canvas_clear_button = $("canvas-clear")
, text = $("text")
, text_options_form = $("text-options")
, text_filename = $("text-filename")
, html = $("html")
, html_options_form = $("html-options")
, html_filename = $("html-filename")
, ctx = canvas.getContext("2d")
, drawing = false
, x_points = session.x_points || []
, y_points = session.y_points || []
, drag_points = session.drag_points || []
, add_point = function(x, y, dragging) {
x_points.push(x);
y_points.push(y);
drag_points.push(dragging);
}
, draw = function(){
canvas.width = canvas.width;
ctx.lineWidth = 6;
ctx.lineJoin = "round";
ctx.strokeStyle = "#000000";
var
i = 0
, len = x_points.length
;
for(; i < len; i++) {
ctx.beginPath();
if (i && drag_points[i]) {
ctx.moveTo(x_points[i-1], y_points[i-1]);
} else {
ctx.moveTo(x_points[i]-1, y_points[i]);
}
ctx.lineTo(x_points[i], y_points[i]);
ctx.closePath();
ctx.stroke();
}
}
, stop_drawing = function() {
drawing = false;
}
// Title guesser and document creator available at https://gist.github.com/1059648
, guess_title = function(doc) {
var
h = "h6 h5 h4 h3 h2 h1".split(" ")
, i = h.length
, headers
, header_text
;
while (i--) {
headers = doc.getElementsByTagName(h[i]);
for (var j = 0, len = headers.length; j < len; j++) {
header_text = headers[j].textContent.trim();
if (header_text) {
return header_text;
}
}
}
}
, doc_impl = document.implementation
, create_html_doc = function(html) {
var
dt = doc_impl.createDocumentType('html', null, null)
, doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
, doc_el = doc.documentElement
, head = doc_el.appendChild(doc.createElement("head"))
, charset_meta = head.appendChild(doc.createElement("meta"))
, title = head.appendChild(doc.createElement("title"))
, body = doc_el.appendChild(doc.createElement("body"))
, i = 0
, len = html.childNodes.length
;
charset_meta.setAttribute("charset", html.ownerDocument.characterSet);
for (; i < len; i++) {
body.appendChild(doc.importNode(html.childNodes.item(i), true));
}
var title_text = guess_title(doc);
if (title_text) {
title.appendChild(doc.createTextNode(title_text));
}
return doc;
}
;
canvas.width = 500;
canvas.height = 300;
if (typeof x_points === "string") {
x_points = JSON.parse(x_points);
} if (typeof y_points === "string") {
y_points = JSON.parse(y_points);
} if (typeof drag_points === "string") {
drag_points = JSON.parse(drag_points);
} if (session.canvas_filename) {
canvas_filename.value = session.canvas_filename;
} if (session.text) {
text.value = session.text;
} if (session.text_filename) {
text_filename.value = session.text_filename;
} if (session.html) {
html.innerHTML = session.html;
} if (session.html_filename) {
html_filename.value = session.html_filename;
}
drawing = true;
draw();
drawing = false;
canvas_clear_button.addEventListener("click", function() {
canvas.width = canvas.width;
x_points.length =
y_points.length =
drag_points.length =
0;
}, false);
canvas.addEventListener("mousedown", function(event) {
event.preventDefault();
drawing = true;
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false);
draw();
}, false);
canvas.addEventListener("mousemove", function(event) {
if (drawing) {
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true);
draw();
}
}, false);
canvas.addEventListener("mouseup", stop_drawing, false);
canvas.addEventListener("mouseout", stop_drawing, false);
canvas_options_form.addEventListener("submit", function(event) {
event.preventDefault();
canvas.toBlobHD(function(blob) {
saveAs(
blob
, (canvas_filename.value || canvas_filename.placeholder) + ".png"
);
}, "image/png");
}, false);
text_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var BB = get_blob();
saveAs(
new BB(
[text.value || text.placeholder]
, {type: "text/plain;charset=" + document.characterSet}
)
, (text_filename.value || text_filename.placeholder) + ".txt"
);
}, false);
html_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var
BB = get_blob()
, xml_serializer = new XMLSerializer()
, doc = create_html_doc(html)
;
saveAs(
new BB(
[xml_serializer.serializeToString(doc)]
, {type: "application/xhtml+xml;charset=" + document.characterSet}
)
, (html_filename.value || html_filename.placeholder) + ".xhtml"
);
}, false);
view.addEventListener("unload", function() {
session.x_points = JSON.stringify(x_points);
session.y_points = JSON.stringify(y_points);
session.drag_points = JSON.stringify(drag_points);
session.canvas_filename = canvas_filename.value;
session.text = text.value;
session.text_filename = text_filename.value;
session.html = html.innerHTML;
session.html_filename = html_filename.value;
}, false);
}(self));
The html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US-x-Hixie">
<head>
<meta charset="utf-8"/>
<title>FileSaver.js demo</title>
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/eligrey/FileSaver.js/702cd2e820b680f88a0f299e33085c196806fc52/demo/demo.css"/>
</head>
<body>
<h1>FileSaver.js demo</h1>
<p>
The following examples demonstrate how it is possible to generate and save any type of data right in the browser using the <code>saveAs()</code> FileSaver interface, without contacting any servers.
</p>
<section id="image-demo">
<h2>Saving an image</h2>
<canvas class="input" id="canvas" width="500" height="300"/>
<form id="canvas-options">
<label>Filename: <input type="text" class="filename" id="canvas-filename" placeholder="doodle"/>.png</label>
<input type="submit" value="Save"/>
<input type="button" id="canvas-clear" value="Clear"/>
</form>
</section>
<section id="text-demo">
<h2>Saving text</h2>
<textarea class="input" id="text" placeholder="Once upon a time..."/>
<form id="text-options">
<label>Filename: <input type="text" class="filename" id="text-filename" placeholder="a plain document"/>.txt</label>
<input type="submit" value="Save"/>
</form>
</section>
<section id="html-demo">
<h2>Saving rich text</h2>
<div class="input" id="html" contenteditable="">
<h3>Some example rich text</h3>
<ul>
<li><del>Plain</del> <ins>Boring</ins> text.</li>
<li><em>Emphasized text!</em></li>
<li><strong>Strong text!</strong></li>
<li>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="70" height="70">
<circle cx="35" cy="35" r="35" fill="red"/>
<text x="10" y="40">image</text>
</svg>
</li>
<li>A link.</li>
</ul>
</div>
<form id="html-options">
<label>Filename: <input type="text" class="filename" id="html-filename" placeholder="a rich document"/>.xhtml</label>
<input type="submit" value="Save"/>
</form>
</section>
<script async="" src="https://cdn.rawgit.com/eligrey/Blob.js/0cef2746414269b16834878a8abc52eb9d53e6bd/Blob.js"/>
<script async="" src="https://cdn.rawgit.com/eligrey/canvas-toBlob.js/f1a01896135ab378aa5c0118eadd81da55e698d8/canvas-toBlob.js"/>
<script async="" src="https://cdn.rawgit.com/eligrey/FileSaver.js/e9d941381475b5df8b7d7691013401e171014e89/FileSaver.min.js"/>
<script async="" src="https://cdn.rawgit.com/eligrey/FileSaver.js/597b6cd0207ce408a6d34890b5b2826b13450714/demo/demo.js"/>
</body>
</html>
Firstly, nothing in the code you've show is related to node.js - so using fileSaver.js without node.js is not an issue
The simplest example I can come up with to demonstrate how to use it using a Blob and a File is as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!-- you'll need to host fileSaver.js on your own host -->
<script src="fileSaver.js"></script>
</head>
<body>
<div id="source">This is some text</div>
<input id="saveFile" type="button" value="saveFile" />
<script>
document.getElementById('saveFile').addEventListener('click', function(e) {
var text = document.getElementById('source').innerHTML;
var file = new File([text], "hello world.txt", {type: "text/plain;charset=utf-8"});
// save it
saveAs(file);
});
</script>
</body>
</html>

How do I play and pause the audio with a button?

How do I create a single button (button will be displayed in index.php) that plays AND pauses audio source node in JavaScript?
So essentially you have a button that plays an audio, and when clicked again, it pauses the song...
EDIT: index.php
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="HTML5 Audio Spectrum Visualizer">
<title>HTML5 Audio API showcase | Audio visualizer</title>
<link type="text/css" rel="stylesheet" href="style/style.css">
</head>
<body>
<div id="wrapper">
<div id="fileWrapper" class="file_wrapper">
<div id="info">
HTML5 Audio API showcase | An Audio Viusalizer
</div>
<label for="uploadedFile">Drag&drop or select a file to play:
</label>
<input type="file" id="uploadedFile"></input>
</div>
<div id="visualizer_wrapper">
<canvas id='canvas' width="800" height="350"></canvas>
</div>
</div>
<footer>
<small></small>
</footer>
<script type="text/javascript" src="js/html5_audio_visualizer.js">
</script>
</body>
</html>
Here is part of the JavaScript code:
window.onload = function() {
new Visualizer().ini();
};
var Visualizer = function() {
this.file = null; //the current file
this.fileName = null; //the current file name
this.audioContext = null;
this.source = null; //the audio source
this.info = document.getElementById('info').innerHTML; //this used to
upgrade the UI information
this.infoUpdateId = null; //to sotore the setTimeout ID and clear the
interval
this.animationId = null;
this.status = 0; //flag for sound is playing 1 or stopped 0
this.forceStop = false;
this.allCapsReachBottom = false;
}
Visualizer.prototype = {
ini: function() {
this._prepareAPI();
this._addEventListner();
},
_prepareAPI: function() {
//fix browser vender for AudioContext and requestAnimationFrame
window.AudioContext = window.AudioContext || window.webkitAudioContext
|| window.mozAudioContext || window.msAudioContext;
window.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame;
window.cancelAnimationFrame = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame ||
window.msCancelAnimationFrame;
try {
this.audioContext = new AudioContext();
} catch (e) {
this._updateInfo('!Your browser does not support AudioContext',
false);
console.log(e);
}
},
_addEventListner: function() {
var that = this,
audioInput = document.getElementById('uploadedFile'),
dropContainer = document.getElementsByTagName("canvas")[0];
//listen the file upload
audioInput.onchange = function() {
if (that.audioContext===null) {return;};
//the if statement fixes the file selction cancle, because the
onchange will trigger even the file selection been canceled
if (audioInput.files.length !== 0) {
//only process the first file
that.file = audioInput.files[0];
that.fileName = that.file.name;
if (that.status === 1) {
//the sound is still playing but we upload another file, so
set the forceStop flag to true
that.forceStop = true;
};
document.getElementById('fileWrapper').style.opacity = 1;
that._updateInfo('Uploading', true);
//once the file is ready,start the visualizer
that._start();
};
};
//listen the drag & drop
dropContainer.addEventListener("dragenter", function() {
document.getElementById('fileWrapper').style.opacity = 1;
that._updateInfo('Drop it on the page', true);
}, false);
dropContainer.addEventListener("dragover", function(e) {
e.stopPropagation();
e.preventDefault();
//set the drop mode
e.dataTransfer.dropEffect = 'copy';
}, false);
dropContainer.addEventListener("dragleave", function() {
document.getElementById('fileWrapper').style.opacity = 0.2;
that._updateInfo(that.info, false);
}, false);
dropContainer.addEventListener("drop", function(e) {
e.stopPropagation();
e.preventDefault();
if (that.audioContext===null) {return;};
document.getElementById('fileWrapper').style.opacity = 1;
that._updateInfo('Uploading', true);
//get the dropped file
that.file = e.dataTransfer.files[0];
if (that.status === 1) {
document.getElementById('fileWrapper').style.opacity = 1;
that.forceStop = true;
};
that.fileName = that.file.name;
//once the file is ready,start the visualizer
that._start();
}, false);
},
_start: function() {
//read and decode the file into audio array buffer
var that = this,
file = this.file,
fr = new FileReader();
fr.onload = function(e) {
var fileResult = e.target.result;
var audioContext = that.audioContext;
if (audioContext === null) {
return;
};
that._updateInfo('Decoding the audio', true);
audioContext.decodeAudioData(fileResult, function(buffer) {
that._updateInfo('Decode succussfully,start the visualizer',
true);
that._visualize(audioContext, buffer);
}, function(e) {
that._updateInfo('!Fail to decode the file', false);
console.log(e);
});
};
fr.onerror = function(e) {
that._updateInfo('!Fail to read the file', false);
console.log(e);
};
//assign the file to the reader
this._updateInfo('Starting read the file', true);
fr.readAsArrayBuffer(file);
},
_visualize: function(audioContext, buffer) {
var audioBufferSouceNode = audioContext.createBufferSource(),
analyser = audioContext.createAnalyser(),
that = this;
//connect the source to the analyser
audioBufferSouceNode.connect(analyser);
//connect the analyser to the destination(the speaker), or we won't
hear the sound
analyser.connect(audioContext.destination);
//then assign the buffer to the buffer source node
audioBufferSouceNode.buffer = buffer;
//play the source
if (!audioBufferSouceNode.start) {
audioBufferSouceNode.start = audioBufferSouceNode.noteOn //in old
browsers use noteOn method
audioBufferSouceNode.stop = audioBufferSouceNode.noteOff //in old
browsers use noteOn method
};
//stop the previous sound if any
if (this.animationId !== null) {
cancelAnimationFrame(this.animationId);
}
if (this.source !== null) {
this.source.stop(0);
}
audioBufferSouceNode.start(0);
this.status = 1;
this.source = audioBufferSouceNode;
audioBufferSouceNode.onended = function() {
that._audioEnd(that);
};
this._updateInfo('Playing ' + this.fileName, false);
this.info = 'Playing ' + this.fileName;
document.getElementById('fileWrapper').style.opacity = 0.2;
this._drawSpectrum(analyser);
},
...
How do I go about doing it? Also is it possible to create a basic volume slider-bar?

How can I let user paste image data from the clipboard into a canvas element in Firefox in pure Javascript?

I have done my best to find a simple, relevant, and up-to-date example that works for the latest version of Firefox and I'm really struggling.
Titles says it all really. I want the user to able to copy part of an image from an editor such as Windows Paint or use the Print Screen button and then paste that into a canvas element. Bonus points if the canvas resizes to fit exactly the pasted image (literally).
Want to avoid Flash or Java based solutions if reasonable.
I'm half-decent at Javascript but relatively inexperienced with the latest HTML5 features and totally new to the Canvas element. Please help!
Version 2.0: Smaller, cleaner code works on Chrome, Firefox, Edge, Opera. No more hacks. But if you need support IE and Safari, check v1 version.
http://jsfiddle.net/viliusl/xq2aLj4b/5/
Version 1.0
Chrome implementation is simple. Firefox (and IE) has restrictions that user must give command to do paste like keyboard event and editable input must be focused, so we do tricks here - on ctrl down we focusthat input field, on release unfocus.
Browser support (image data):
Firefox
Chrome
Edge
IE-11
Opera
var CLIPBOARD = new CLIPBOARD_CLASS("my_canvas", true);
/**
* image pasting into canvas
*
* #param {string} canvas_id - canvas id
* #param {boolean} autoresize - if canvas will be resized
*/
function CLIPBOARD_CLASS(canvas_id, autoresize) {
var _self = this;
var canvas = document.getElementById(canvas_id);
var ctx = document.getElementById(canvas_id).getContext("2d");
var ctrl_pressed = false;
var command_pressed = false;
var paste_event_support;
var pasteCatcher;
//handlers
document.addEventListener('keydown', function (e) {
_self.on_keyboard_action(e);
}, false); //firefox fix
document.addEventListener('keyup', function (e) {
_self.on_keyboardup_action(e);
}, false); //firefox fix
document.addEventListener('paste', function (e) {
_self.paste_auto(e);
}, false); //official paste handler
//constructor - we ignore security checks here
this.init = function () {
pasteCatcher = document.createElement("div");
pasteCatcher.setAttribute("id", "paste_ff");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;width:10px;margin-left:-20px;';
document.body.appendChild(pasteCatcher);
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (paste_event_support === true || ctrl_pressed == false || mutation.type != 'childList'){
//we already got data in paste_auto()
return true;
}
//if paste handle failed - capture pasted object manually
if(mutation.addedNodes.length == 1) {
if (mutation.addedNodes[0].src != undefined) {
//image
_self.paste_createImage(mutation.addedNodes[0].src);
}
//register cleanup after some time.
setTimeout(function () {
pasteCatcher.innerHTML = '';
}, 20);
}
});
});
var target = document.getElementById('paste_ff');
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);
}();
//default paste action
this.paste_auto = function (e) {
paste_event_support = false;
if(pasteCatcher != undefined){
pasteCatcher.innerHTML = '';
}
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
paste_event_support = true;
//access data directly
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
//image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
this.paste_createImage(source);
}
}
e.preventDefault();
}
else {
//wait for DOMSubtreeModified event
//https://bugzilla.mozilla.org/show_bug.cgi?id=891247
}
}
};
//on keyboard press
this.on_keyboard_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey) {
if (ctrl_pressed == false)
ctrl_pressed = true;
}
//v
if (k == 86) {
if (document.activeElement != undefined && document.activeElement.type == 'text') {
//let user paste into some input
return false;
}
if (ctrl_pressed == true && pasteCatcher != undefined){
pasteCatcher.focus();
}
}
};
//on kaybord release
this.on_keyboardup_action = function (event) {
//ctrl
if (event.ctrlKey == false && ctrl_pressed == true) {
ctrl_pressed = false;
}
//command
else if(event.metaKey == false && command_pressed == true){
command_pressed = false;
ctrl_pressed = false;
}
};
//draw pasted image to canvas
this.paste_createImage = function (source) {
var pastedImage = new Image();
pastedImage.onload = function () {
if(autoresize == true){
//resize
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
}
else{
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage.src = source;
};
}
1. Copy image data into clipboard or press Print Screen <br>
2. Press Ctrl+V (page/iframe must be focused):
<br /><br />
<canvas style="border:1px solid grey;" id="my_canvas" width="300" height="300"></canvas>
ViliusL's answer is great, but for those looking for a simple cross-browser way to capture a pasted image:
window.addEventListener("paste", async function(e) {
e.preventDefault();
e.stopPropagation();
let file = e.clipboardData.items[0].getAsFile();
let objectUrl = URL.createObjectURL(file);
// do something with url here
});
You'll probably want to do some error checking (like in ViliusL's answer), in case they paste something that's not an image. According to MDN, clipboardData works in all modern browsers. I've tested on Chrome and Firefox, and they work fine.

Categories