This example does pretty much what I would like to port in Angular-js: HTML5 File API.
I have been trying to google some example of directives however I found old example that do massive use of DOM or are not written for Angular 1.0.4.
Basically this is the pure js code:
var holder = document.getElementById('holder'),
state = document.getElementById('status');
if (typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'File API & FileReader available';
}
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
console.log(file);
reader.readAsDataURL(file);
return false;
};
The only possible way I can think of is creating a directive that does
edo.directive('fileDrag', function () {
return {
restrict: 'A',
link: function (scope, elem) {
elem.bind('ondrop', function(e){
e.preventDefault();
var file = e.dataTransfer.files[0], reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
console.log(file);
reader.readAsDataURL(file);
return false;
});
}
};
});
However (1) it did not work, (2) before I fix it I would like to know if something exists or if I am doing it properly,
Any hint or help is very much appreciated.
To consolidate the comments into an answer, change ondrop to drop, add e.stopPropagation(), change holder to elem.
edo.directive('fileDrag', function () {
return {
restrict: 'A',
link: function (scope, elem) {
elem.bind('drop', function(e){
e.preventDefault();
e..stopPropagation();
var file = e.dataTransfer.files[0], reader = new FileReader();
reader.onload = function (event) {
console.log(event.target);
elem.style.background = 'url(' + event.target.result + ') no-repeat center';
};
console.log(file);
reader.readAsDataURL(file);
return false;
});
}
};
});
I was doing something similar and here is my working solution:
HTML
app.directive("dropzone", function() {
return {
restrict : "A",
link: function (scope, elem) {
elem.bind('drop', function(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.readAsArrayBuffer(f);
reader.onload = (function(theFile) {
return function(e) {
var newFile = { name : theFile.name,
type : theFile.type,
size : theFile.size,
lastModifiedDate : theFile.lastModifiedDate
}
scope.addfile(newFile);
};
})(f);
}
});
}
}
});
div[dropzone] {
border: 2px dashed #bbb;
border-radius: 5px;
padding: 25px;
text-align: center;
font: 20pt bold;
color: #bbb;
margin-bottom: 20px;
}
<div dropzone>Drop Files Here</div>
Preventing default events, and getting file from original event. All can be implemented in directive. You should pass function, for work with files to attribute on-file-drop. Also 'dragging' class is added to dropzone element while dragging.
In view it looks like this:
<div file-dropzone on-file-drop="myFunction">This is my dropzone </div>
directive:
function fileDropzoneDirective() {
return {
restrict: 'A',
link: fileDropzoneLink
};
function fileDropzoneLink($scope, element, attrs) {
element.bind('dragover', processDragOverOrEnter);
element.bind('dragenter', processDragOverOrEnter);
element.bind('dragend', endDragOver);
element.bind('dragleave', endDragOver);
element.bind('drop', dropHandler);
function dropHandler(angularEvent) {
var event = angularEvent.originalEvent || angularEvent;
var file = event.dataTransfer.files[0];
event.preventDefault();
$scope.$eval(attrs.onFileDrop)(file);
}
function processDragOverOrEnter(angularEvent) {
var event = angularEvent.originalEvent || angularEvent;
if (event) {
event.preventDefault();
}
event.dataTransfer.effectAllowed = 'copy';
element.addClass('dragging');
return false;
}
function endDragOver() {
element.removeClass('dragging');
}
}
}
Related
In my application I generate a circle using the HTML element canvas.
The generation of the circle works well: the circle is correctly rendered.
The problem is that I have to put that circle in an option of a select, and as far as I know is not possible to put a canvas inside an option, therefore I probably have to convert the canvas to a base64 image so that I should be able to use it as a background-image of the option.
However, the conversion from canvas to base64 image is not working, as the browser is rendering a blank image.
I have created a fiddle for troubleshooting: https://jsfiddle.net/4hfmp0cs/
Here below you can see the javascript code of the fiddle.
function foo()
{
var circle = getStateCircle("opened");
//var gl = circle.getContext("webgl", { preserveDrawingBuffer: true });
var dataUrl = circle.toDataURL("image/png");
var img = document.createElement("img");
img.src = dataUrl;
document.getElementById("container").appendChild(img);
}
function getStateCircle(state)
{
var stateCircle;
if(state === "opened")
{
stateCircle = new Circle("#ffcc00", "20px");
}
else if(state === "accepted")
{
stateCircle = new Circle("#33cc33", "20px");
}
else if (state === "refused")
{
stateCircle = new Circle("#ff3300", "20px");
}
else if (state === "closed")
{
stateCircle = new Circle("black", "20px");
}
else
{
throw new Error("The state of the offer is unknown");
}
stateCircle.buildCircle();
var circle = stateCircle.getCircle();
return circle;
}
function Circle(color, size)
{
this._color = color;
this._size = size;
this._circle;
this.buildCircle = function()
{
var style = {
borderRadius: "50%",
backgroundColor: this._color,
height: this._size,
width: this._size
}
this._circle = new ElementBuilder("canvas").withStyleObject(style).getElement();
}
this.buildCircleAndAppendTo = function(father)
{
this._buildCircle();
father.appendChild(this._circle);
}
this.getCircle = function()
{
return this._circle;
}
}
function ElementBuilder(elementName) {
var This = this;
this.element = document.createElement(elementName);
this.withName = function (name)
{
this.element.setAttribute("name", name);
return this;
};
this.withAttribute = function (attributeName, attributeValue)
{
this.element.setAttribute(attributeName, attributeValue);
return this;
};
this.withId = function (id)
{
this.element.setAttribute("id", id);
return this;
}
this.withClass = function (className)
{
this.element.setAttribute("class", className);
return this;
}
this.addClass = function (className)
{
this.element.className = this.element.className + " " + className;
return this;
}
this.withTextContent = function (text)
{
this.element.textContent = text;
return this;
}
this.withValue = function (value)
{
this.element.value = value;
return this;
}
this.getElement = function ()
{
return this.element;
};
this.withChild = function (child)
{
this.element.appendChild(child);
return this;
};
this.withEventListener = function (type, func)
{
this.element.addEventListener(type, func);
return this;
};
this.withClickEventListener = function (func)
{
this.element.addEventListener("click", func);
return this;
}
this.withDoubleClickEventListener = function (func)
{
this.element.addEventListener("dblclick", func);
return this;
}
this.withStyle = function (styleAttribute, value)
{
this.element.style[styleAttribute] = value;
return this;
}
this.withStyleObject = function (styleObject)
{
ensureIsAnObject(styleObject);
var keys = Object.keys(styleObject);
keys.forEach(function (elt) {
This.withStyle(elt, styleObject[elt]);
});
return this;
}
}
function ensureIsAnObject(value, argumentName) {
if (!(typeof value == "object")) {
throw new Error("The argument '" + argumentName + "' should be an object, but it's type is --->" + typeof value);
}
}
The HTML code
<div id="container">
</div>
<button onclick="foo()">Append image</button>
Nowhere are you actually drawing to the canvas, just styling it with css, which is rendered separate from the canvas. You can replace the canvas with a div, or any other block element and just append that to the document to get the correct effect.
Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
Or Check in
http://jsfiddle.net/simonsarris/vgmFN/
I'm trying to implement drag and drop angular directive to my application that to render d3 collapsible tree. Now I'm using basic Input method that user can load file from local machine. And with "Input" everything works and renders fine, but I've got requirements that I have to implement drop zone, so I found in internet this example, cause the example has been provided for images, I've a little modified it for json files:
<div id="left-input" class="dropzone" file-dropzone="[application/json]" file="json" file-name="applicationFileName" data-max-file-size="3">
<span>Drop Image Here</span></div>
<span class="dropzone">{{applicationFileName}}</span>
and set it up for d3 library but how I can see thru console.log my variable is underfined, so if I'm checking variable in directive:
reader = new FileReader();
reader.onload = function(evt) {
scope.file = evt.target.result;
console.log(scope.file);
if (checkSize(size) && isTypeValid(type)) {
return scope.$apply(function() {
scope.file = evt.target.result;
if (angular.isString(scope.fileName)) {
return scope.fileName = name;
}
});
}
};
so console.log(scope.file) return me exactly my variable
but when I'm using this variable in controller inside of d3 function:
$scope.load_left = function () {
// Get JSON data
console.log('['+ $scope.file +']');
root = $scope.file;
treeData = JSON.parse(root);
//d3.json($scope.result, function (error, treeData) {
it returns me undefined
so where did I mistake?
this my dnd directive:
app.directive('fileDropzone', function() {
return {
restrict: '',
scope: {
file: '=',
fileName: '='
},
link: function(scope, element, attrs) {
var checkSize, isTypeValid, processDragOverOrEnter, validMimeTypes;
processDragOverOrEnter = function(event) {
if (event != null) {
event.preventDefault();
}
event.dataTransfer.effectAllowed = 'copy';
return false;
};
validMimeTypes = attrs.fileDropzone;
checkSize = function(size) {
var _ref;
if (((_ref = attrs.maxFileSize) === (void 0) || _ref === '') || (size / 1024) / 1024 < attrs.maxFileSize) {
return true;
} else {
alert("File must be smaller than " + attrs.maxFileSize + " MB");
return false;
}
};
isTypeValid = function(type) {
if ((validMimeTypes === (void 0) || validMimeTypes === '') || validMimeTypes.indexOf(type) > -1) {
return true;
} else {
alert("Invalid file type. File must be one of following types " + validMimeTypes);
return false;
}
};
element.bind('dragover', processDragOverOrEnter);
element.bind('dragenter', processDragOverOrEnter);
return element.bind('drop', function(event) {
var file, name, reader, size, type;
if (event != null) {
event.preventDefault();
}
reader = new FileReader();
reader.onload = function(evt) {
scope.file = evt.target.result;
console.log(scope.file);
if (checkSize(size) && isTypeValid(type)) {
return scope.$apply(function() {
scope.file = evt.target.result;
if (angular.isString(scope.fileName)) {
return scope.fileName = name;
}
});
}
};
console.log('['+ scope.file +']');
file = event.dataTransfer.files[0];
//console.log('['+ file +']');
name = file.name;
type = file.type;
size = file.size;
reader.readAsText(file);
//reader.readAsDataURL(file);
return false;
});
}
};
});
and thru this function I'm rendering my d3 tree
$scope.load_left = function () {
// Get JSON data
console.log('['+ $scope.file +']');
root = $scope.file;
treeData = JSON.parse(root);
//d3.json($scope.result, function (error, treeData) {
Also I'm providing code with my old Input method
<div style="display: flex">
<input type="file" id="left-input"/>
<button class="btn btn-info" ng-click="load_left()">Load It</button>
</div>
$scope.leftWindow = function (e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var leftcontent = e.target.result;
displayLeftContents(leftcontent);
};
reader.readAsText(file);
};
function displayLeftContents(leftcontent) {
$scope.leftContent = JSON.parse(leftcontent);
$scope.$apply();
}
document.getElementById('left-input')
.addEventListener('change', $scope.leftWindow, false);
$scope.load_left = function () {
// Get JSON data
root = JSON.stringify($scope.leftContent);
//console.log('['+ root +']');
treeData = JSON.parse(root);
//console.log(treeData);
//d3.json($scope.result, function (error, treeData) {
Just want to post how I've resolved this problem, may be somebody will need it.
so I'have added on more directive for reading files and then set up the variable to d3 function inside controller, so the full code looks like:
app.directive('fileDropzone', function() {
return {
restrict: '',
scope: {
file: '=',
fileName: '='
},
link: function(scope, element, attrs) {
var checkSize, isTypeValid, processDragOverOrEnter, validMimeTypes;
processDragOverOrEnter = function(event) {
if (event != null) {
event.preventDefault();
}
event.dataTransfer.effectAllowed = 'copy';
return false;
};
validMimeTypes = attrs.fileDropzone;
checkSize = function(size) {
var _ref;
if (((_ref = attrs.maxFileSize) === (void 0) || _ref === '') || (size / 1024) / 1024 < attrs.maxFileSize) {
return true;
} else {
alert("File must be smaller than " + attrs.maxFileSize + " MB");
return false;
}
};
isTypeValid = function(type) {
if ((validMimeTypes === (void 0) || validMimeTypes === '') || validMimeTypes.indexOf(type) > -1) {
return true;
} else {
alert("Invalid file type. File must be one of following types " + validMimeTypes);
return false;
}
};
element.bind('dragover', processDragOverOrEnter);
element.bind('dragenter', processDragOverOrEnter);
//console.log(element.bind('dragenter', processDragOverOrEnter));
return element.bind('drop', function(event) {
var file, name, reader, size, type;
if (event != null) {
event.preventDefault();
}
reader = new FileReader();
reader.onload = function(evt) {
scope.$apply(function() {
$LeftfileDrop = evt.target.result;
$RightfileDrop = evt.target.result;
});
if (checkSize(size) && isTypeValid(type)) {
return scope.$apply(function() {
scope.file = evt.target.result;
if (angular.isString(scope.fileName)) {
return scope.fileName = name;
}
});
}
};
file = event.dataTransfer.files[0];
console.log(file);
name = file.name;
type = file.type;
size = file.size;
reader.readAsText(file);
return false;
});
}
};
});
app.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
and d3 function:
// Get JSON data
root = $LeftfileDrop;
treeData = JSON.parse(root);
//d3.json($scope.result, function (error, treeData) {
I am using angular-dragdrop.js.
URL: http://angular-dragdrop.github.io/angular-dragdrop/ in my project for drag and drop functionality.
I am facing some issue while using Input type text. It is not working in only IE browser. IE 11 and IE 10.
Problem -
onCLick on input box focus is coming but cursor inside the input box is not coming.
HTML Code:
<div ng-repeat="(name, panel) in row.panels"
class="panel"
ui-draggable="true" drag="panel.id"
ui-on-Drop="onDrop($data, row, panel)"
drag-handle-class="drag-handle" panel-width ng-model="panel">
<input type="text"/>
<grafana-panel type="panel.type" ng-cloak></grafana-panel>
</div>
<div ng-repeat="(name, panel) in row.panels"
class="panel"
ui-draggable="false" drag="panel.id"
ui-on-Drop="onDrop($data, row, panel)"
drag-handle-class="drag-handle" panel-width ng-model="panel">
<input type="text"/>
<grafana-panel type="panel.type" ng-cloak></grafana-panel>
</div>
for ui-draggable false it is working. but for ui-draggable true its not working.
Vendor JS file:
/**
* Created with IntelliJ IDEA.
* User: Ganaraj.Pr
* Date: 11/10/13
* Time: 11:27
* To change this template use File | Settings | File Templates.
*/
(function(angular){
function isDnDsSupported(){
return 'ondrag' in document.createElement("a");
}
if(!isDnDsSupported()){
angular.module("ang-drag-drop", []);
return;
}
if (window.jQuery && (-1 == window.jQuery.event.props.indexOf("dataTransfer"))) {
window.jQuery.event.props.push("dataTransfer");
}
var currentData;
angular.module("ang-drag-drop",[])
.directive("uiDraggable", [
'$parse',
'$rootScope',
'$dragImage',
function ($parse, $rootScope, $dragImage) {
return function (scope, element, attrs) {
var dragData = "",
isDragHandleUsed = false,
dragHandleClass,
draggingClass = attrs.draggingClass || "on-dragging",
dragTarget;
element.attr("draggable", false);
attrs.$observe("uiDraggable", function (newValue) {
if(newValue){
element.attr("draggable", newValue);
}
else{
element.removeAttr("draggable");
}
});
if (attrs.drag) {
scope.$watch(attrs.drag, function (newValue) {
dragData = newValue || "";
});
}
if (angular.isString(attrs.dragHandleClass)) {
isDragHandleUsed = true;
dragHandleClass = attrs.dragHandleClass.trim() || "drag-handle";
element.bind("mousedown", function (e) {
dragTarget = e.target;
});
}
function dragendHandler(e) {
setTimeout(function() {
element.unbind('$destroy', dragendHandler);
}, 0);
var sendChannel = attrs.dragChannel || "defaultchannel";
$rootScope.$broadcast("ANGULAR_DRAG_END", sendChannel);
if (e.dataTransfer && e.dataTransfer.dropEffect !== "none") {
if (attrs.onDropSuccess) {
var fn = $parse(attrs.onDropSuccess);
scope.$evalAsync(function () {
fn(scope, {$event: e});
});
} else {
if (attrs.onDropFailure) {
var fn = $parse(attrs.onDropFailure);
scope.$evalAsync(function () {
fn(scope, {$event: e});
});
}
}
}
element.removeClass(draggingClass);
}
element.bind("dragend", dragendHandler);
element.bind("dragstart", function (e) {
var isDragAllowed = !isDragHandleUsed || dragTarget.classList.contains(dragHandleClass);
if (isDragAllowed) {
var sendChannel = attrs.dragChannel || "defaultchannel";
var sendData = angular.toJson({ data: dragData, channel: sendChannel });
var dragImage = attrs.dragImage || null;
element.addClass(draggingClass);
element.bind('$destroy', dragendHandler);
if (dragImage) {
var dragImageFn = $parse(attrs.dragImage);
scope.$evalAsync(function() {
var dragImageParameters = dragImageFn(scope, {$event: e});
if (dragImageParameters) {
if (angular.isString(dragImageParameters)) {
dragImageParameters = $dragImage.generate(dragImageParameters);
}
if (dragImageParameters.image) {
var xOffset = dragImageParameters.xOffset || 0,
yOffset = dragImageParameters.yOffset || 0;
e.dataTransfer.setDragImage(dragImageParameters.image, xOffset, yOffset);
}
}
});
}
e.dataTransfer.setData("Text", sendData);
currentData = angular.fromJson(sendData);
e.dataTransfer.effectAllowed = "copyMove";
$rootScope.$broadcast("ANGULAR_DRAG_START", sendChannel, currentData.data);
}
else {
e.preventDefault();
}
});
};
}
])
.directive("uiOnDrop", [
'$parse',
'$rootScope',
function ($parse, $rootScope) {
return function (scope, element, attr) {
var dragging = 0; //Ref. http://stackoverflow.com/a/10906204
var dropChannel = attr.dropChannel || "defaultchannel" ;
var dragChannel = "";
var dragEnterClass = attr.dragEnterClass || "on-drag-enter";
var dragHoverClass = attr.dragHoverClass || "on-drag-hover";
var customDragEnterEvent = $parse(attr.onDragEnter);
var customDragLeaveEvent = $parse(attr.onDragLeave);
function onDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
if (e.stopPropagation) {
e.stopPropagation();
}
var fn = $parse(attr.uiOnDragOver);
scope.$evalAsync(function () {
fn(scope, {$event: e, $channel: dropChannel});
});
e.dataTransfer.dropEffect = e.shiftKey ? 'copy' : 'move';
return false;
}
function onDragLeave(e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
dragging--;
if (dragging == 0) {
scope.$evalAsync(function () {
customDragEnterEvent(scope, {$event: e});
});
element.removeClass(dragHoverClass);
}
var fn = $parse(attr.uiOnDragLeave);
scope.$evalAsync(function () {
fn(scope, {$event: e, $channel: dropChannel});
});
}
function onDragEnter(e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
dragging++;
var fn = $parse(attr.uiOnDragEnter);
scope.$evalAsync(function () {
fn(scope, {$event: e, $channel: dropChannel});
});
$rootScope.$broadcast("ANGULAR_HOVER", dragChannel);
scope.$evalAsync(function () {
customDragLeaveEvent(scope, {$event: e});
});
element.addClass(dragHoverClass);
}
function onDrop(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
if (e.stopPropagation) {
e.stopPropagation(); // Necessary. Allows us to drop.
}
var sendData = e.dataTransfer.getData("Text");
sendData = angular.fromJson(sendData);
var fn = $parse(attr.uiOnDrop);
scope.$evalAsync(function () {
fn(scope, {$data: sendData.data, $event: e, $channel: sendData.channel});
});
element.removeClass(dragEnterClass);
dragging = 0;
}
function isDragChannelAccepted(dragChannel, dropChannel) {
if (dropChannel === "*") {
return true;
}
var channelMatchPattern = new RegExp("(\\s|[,])+(" + dragChannel + ")(\\s|[,])+", "i");
return channelMatchPattern.test("," + dropChannel + ",");
}
function preventNativeDnD(e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.dataTransfer.dropEffect = "none";
return false;
}
var deregisterDragStart = $rootScope.$on("ANGULAR_DRAG_START", function (event, channel) {
dragChannel = channel;
if (isDragChannelAccepted(channel, dropChannel)) {
if (attr.dropValidate) {
var validateFn = $parse(attr.dropValidate);
var valid = validateFn(scope, {$data: currentData.data, $channel: currentData.channel});
if (!valid) {
element.bind("dragover", preventNativeDnD);
element.bind("dragenter", preventNativeDnD);
element.bind("dragleave", preventNativeDnD);
element.bind("drop", preventNativeDnD);
return;
}
}
element.bind("dragover", onDragOver);
element.bind("dragenter", onDragEnter);
element.bind("dragleave", onDragLeave);
element.bind("drop", onDrop);
element.addClass(dragEnterClass);
}
else {
element.bind("dragover", preventNativeDnD);
element.bind("dragenter", preventNativeDnD);
element.bind("dragleave", preventNativeDnD);
element.bind("drop", preventNativeDnD);
}
});
var deregisterDragEnd = $rootScope.$on("ANGULAR_DRAG_END", function (e, channel) {
dragChannel = "";
if (isDragChannelAccepted(channel, dropChannel)) {
element.unbind("dragover", onDragOver);
element.unbind("dragenter", onDragEnter);
element.unbind("dragleave", onDragLeave);
element.unbind("drop", onDrop);
element.removeClass(dragHoverClass);
element.removeClass(dragEnterClass);
}
element.unbind("dragover", preventNativeDnD);
element.unbind("dragenter", preventNativeDnD);
element.unbind("dragleave", preventNativeDnD);
element.unbind("drop", preventNativeDnD);
});
var deregisterDragHover = $rootScope.$on("ANGULAR_HOVER", function (e, channel) {
if (isDragChannelAccepted(channel, dropChannel)) {
element.removeClass(dragHoverClass);
}
});
scope.$on('$destroy', function () {
deregisterDragStart();
deregisterDragEnd();
deregisterDragHover();
});
attr.$observe('dropChannel', function (value) {
if (value) {
dropChannel = value;
}
});
};
}
])
.constant("$dragImageConfig", {
height: 20,
width: 200,
padding: 10,
font: 'bold 11px Arial',
fontColor: '#eee8d5',
backgroundColor: '#93a1a1',
xOffset: 0,
yOffset: 0
})
.service("$dragImage", [
'$dragImageConfig',
function (defaultConfig) {
var ELLIPSIS = '…';
function fitString(canvas, text, config) {
var width = canvas.measureText(text).width;
if (width < config.width) {
return text;
}
while (width + config.padding > config.width) {
text = text.substring(0, text.length - 1);
width = canvas.measureText(text + ELLIPSIS).width;
}
return text + ELLIPSIS;
};
this.generate = function (text, options) {
var config = angular.extend({}, defaultConfig, options || {});
var el = document.createElement('canvas');
el.height = config.height;
el.width = config.width;
var canvas = el.getContext('2d');
canvas.fillStyle = config.backgroundColor;
canvas.fillRect(0, 0, config.width, config.height);
canvas.font = config.font;
canvas.fillStyle = config.fontColor;
var title = fitString(canvas, text, config);
canvas.fillText(title, 4, config.padding + 4);
var image = new Image();
image.src = el.toDataURL();
return {
image: image,
xOffset: config.xOffset,
yOffset: config.yOffset
};
}
}
]);
}(angular));
URL Demo :
http://plnkr.co/edit/ldGXZbKgHn2YnGGXdYrm?p=preview
input type is not working properly in IE.
Please suggest me any solution or hack.
Thanks!!
I have an HTML file and this contain JavaScript code and works fine, but when I decided put the JS code in different file and call from the HTML file, doesn't work. Why?
The JS code is like this:
(function (document) {
var toggleDocumentationMenu = function () {
var navBtn = document.querySelector('.main-nav1');
var navList = document.querySelector('.main-nav2');
var navIsOpenedClass = 'nav-is-opened';
var navListIsOpened = false;
navBtn.addEventListener('click', function (event) {
event.preventDefault();
if (!navListIsOpened) {
addClass(navList, navIsOpenedClass);
navListIsOpened = true;
} else {
removeClass(navList, navIsOpenedClass);
navListIsOpened = false;
}
});
};
var toggleMainNav = function () {
var documentationItem = document.querySelector('.main-nav3');
var documentationLink = document.querySelector('.main-nav3 > .main-sub-nav');
var documentationIsOpenedClass = 'subnav-is-opened';
var documentationIsOpened = false;
if (documentationLink) {
documentationLink.addEventListener('click', function (event) {
event.preventDefault();
if (!documentationIsOpened) {
documentationIsOpened = true;
addClass(documentationItem, documentationIsOpenedClass);
} else {
documentationIsOpened = false;
removeClass(documentationItem, documentationIsOpenedClass);
}
});
}
};
var isTouch = function () {
return ('ontouchstart' in window) ||
window.DocumentTouch && document instanceof DocumentTouch;
};
var addClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(/\s+$/gi, '') + ' ' + className;
};
var removeClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(className, '');
};
toggleDocumentationMenu();
toggleMainNav();
})(document);
I read it's possible that works if I put like this:
$(document).ready(function() {
// the javascript code here
});
But it still doesn't working.
Now I wonder, It's possible this code works fine in separate file?
Can´t find in the documentation what to do next.
Calling:
PDFView.open('/MyPDFs/Pdf1.pdf', 'auto', null)
I am able to see the blank pages, the loader and also the document gets the number of pages of my PDF.
The only thing is missing is the rendering.
Does anyone knows what I should call next?
Thanks
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call! Thanks
In viewer.js I added call to updateViewarea() after the document was downloaded.
... PDFJS.getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
updateViewarea();
}, ...