Image Preview on hover in jquery - jquery-ui

Below is my code for an image preview on hover. It preview the image in the original size which I don't want.
I'd like to have the previews be a fixed width, say 300px. How do I do that?
Here is my code:
this.imagePreview = function(){
/* CONFIG */
xOffset = 10;
yOffset = 30;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$("a.preview").hover(function(e){
this.t = this.title;
this.title = "";
var c = (this.t != "") ? "<br/>" + this.t : "";
$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");
$("#preview")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px")
.fadeIn("fast");
},
function(){
this.title = this.t;
$("#preview").remove();
});
$("a.preview").mousemove(function(e){
$("#preview")
.css("top",(e.pageY - xOffset) + "px")
.css("left", (e.pageX + yOffset) + "px");
});
};

After this line:
$("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");
You can add:
$("#preview>img").width(300);

Related

How to add Dom element dynamically in angular7

I am using angular 7 and I need to add a Dom element dynamically through the code.
I know the way of doing it in JavaScript
var adiv = document.createElement('div');
adiv.classList.add("redmark");
adiv.style.position = "absolute";
document.body.appendChild(adiv);
adiv.innerHTML = '< img src="css/led_red.png" class="zoom" style="position: absolute;">';
adiv.style.display = "";
adiv.style.left = (position.x - 16) + 'px';
adiv.style.top = (position.y - 32) + 'px';
var markObj = { position: [x, y, z], mark: “as”}
But how to do it in angular?

Fix position mouse cursor

When I drag the svg(red) to another position on the screen, the cursor mouse loses the original angular position (lag) and points to blank area ... I used a var dx and dy in "var point e.clientx" to fix it, unsuccessfully ... any suggestions?
code: http://jsfiddle.net/rebecavascon/evgLhdz3/2/
show: http://jsfiddle.net/rebecavascon/evgLhdz3/2/show/
function updateSVG(e) {
if (follow) {
var centerPoint = new Point(center[0].getAttribute("cx"), center[0].getAttribute("cy"));
var point = new Point(e.clientX, e.clientY);
var angle = Math.round(100 * getAngleFromPoint(point, centerPoint)) / 100;
var distance = Math.round(getDistance(point, centerPoint));
var d = "M " + centerPoint.X + " " + centerPoint.Y + " L " + point.X + " " + point.Y;
path.attr("d", d);
txt.attr("x", point.X);
txt.attr("y", point.Y);
txt.html(distance + arrows + " (" + angle + degree + ")");
txt.attr("transform", "rotate(" + angle + " " + point.X + " " + point.Y + ")");
dynamic.attr("r", distance);
}
fitSVG();
}
Creating an offset worked for my testing.
Code: http://jsfiddle.net/Twisty/8zx8p2wf/19/
Working: http://jsfiddle.net/Twisty/8zx8p2wf/19/show/
Added Function getCenter()
function getCenter(target) {
var b, x, y, w, h, cx, cy;
b = target[0].getBoundingClientRect();
console.log(target, b);
x = b.x;
y = b.y;
w = b.width;
h = b.height;
cx = x + (w / 2);
cy = y + (h / 2);
console.log(x, y, w, h, cx, cy);
return {
X: cx,
Y: cy
};
}
This gets the true center of an SVG Object. Looks like the cx and cy attributes do not get updated.
Updated function updateSVG()
function updateSVG(e) {
if (follow) {
var centerPoint = getCenter(center);
var point = new Point(e.clientX, e.clientY);
var angle = Math.round(100 * getAngleFromPoint(point, centerPoint)) / 100;
var distance = Math.round(getDistance(point, centerPoint));
var od = {
p: {
X: point.X - offset.X,
Y: point.Y - offset.Y
},
cp: {
X: centerPoint.X - offset.X,
Y: centerPoint.Y - offset.Y
}
};
var d = "M" + od.p.X + "," + od.p.Y + " L" + od.cp.X + "," + od.cp.Y;
path.attr("d", d);
txt.attr("x", point.X);
txt.attr("y", point.Y);
txt.html(distance + arrows + " (" + angle + degree + ")");
txt.attr("transform", "rotate(" + angle + " " + point.X + " " + point.Y + ")");
dynamic.attr("r", distance);
}
fitSVG();
}
This uses a new offset constant variable and the correct center points.
JavaScript
$(function() {
var center = $("#center"),
dynamic = $("#dynamic"),
path = $("#deg"),
svg = $("svg"),
txt = $("#txt"),
svgNS = svg[0].namespaceURI,
degree = String.fromCharCode(176),
arrows = String.fromCharCode(845),
follow = true,
startPos,
endPos,
offset = {
X: 0,
Y: 0
};
function Point(x, y) {
return {
"X": x,
"Y": y
};
}
function getCenter(target) {
var b, x, y, w, h, cx, cy;
b = target[0].getBoundingClientRect();
console.log(target, b);
x = b.x;
y = b.y;
w = b.width;
h = b.height;
cx = x + (w / 2);
cy = y + (h / 2);
console.log(x, y, w, h, cx, cy);
return {
X: cx,
Y: cy
};
}
// Credits goes to Stackoverflow: http://stackoverflow.com/a/14413632
function getAngleFromPoint(point, centerPoint) {
var dy = (point.Y - centerPoint.Y),
dx = (point.X - centerPoint.X);
var theta = Math.atan2(dy, dx);
var angle = (((theta * 180) / Math.PI)) % 360;
angle = (angle < 0) ? 360 + angle : angle;
return angle;
}
// Credits goes to http://snipplr.com/view/47207/
function getDistance(point1, point2) {
var xs = 0;
var ys = 0;
xs = point2.X - point1.X;
xs = xs * xs;
ys = point2.Y - point1.Y;
ys = ys * ys;
return Math.sqrt(xs + ys);
}
function fitSVG() {
var width = window.innerWidth,
height = window.innerHeight;
svg.width(width);
svg.height(height);
}
function updateSVG(e) {
if (follow) {
//var centerPoint = new Point(center[0].getAttribute("cx"), center[0].getAttribute("cy"));
var centerPoint = getCenter(center);
var point = new Point(e.clientX, e.clientY);
var angle = Math.round(100 * getAngleFromPoint(point, centerPoint)) / 100;
var distance = Math.round(getDistance(point, centerPoint));
var od = {
p: {
X: point.X - offset.X,
Y: point.Y - offset.Y
},
cp: {
X: centerPoint.X - offset.X,
Y: centerPoint.Y - offset.Y
}
};
var d = "M" + od.p.X + "," + od.p.Y + " L" + od.cp.X + "," + od.cp.Y;
$("#mouse").html(e.clientX + "," + e.clientY);
$("#svgPos").html(svg.position().left + "," + svg.position().top);
$("#offset").html(offset.X + "," + offset.Y);
$("#centerPoint").html(centerPoint.X + "," + centerPoint.Y);
$("#point").html(point.X + "," + point.Y);
$("#path").html(d);
$("#angle").html(angle);
$("#distance").html(distance);
path.attr("d", d);
txt.attr("x", point.X);
txt.attr("y", point.Y);
txt.html(distance + arrows + " (" + angle + degree + ")");
txt.attr("transform", "rotate(" + angle + " " + point.X + " " + point.Y + ")");
dynamic.attr("r", distance);
}
fitSVG();
}
grid_size = 10;
svg
.mousemove(updateSVG)
.click(function() {
follow = !follow;
return true;
});
$(".img").draggable({
handle: "svg",
classes: {
"ui-draggable-dragging": "opac"
},
cursor: "grab",
grid: [grid_size, grid_size],
start: function(e, ui) {
$(this).find(".text").hide();
follow = false;
startPos = ui.position;
},
stop: function() {
follow = true;
endPos = svg.position();
offset.X = endPos.left;
offset.Y = endPos.top;
}
});
});
Through testing, I adjusted the draggable a little bit, such that, the div.img wrapper is the draggable and the svg inside is the handle. I'm not sure if there is a benefit here, yet I didn't want it to go unnoticed.

Center image doc.addImage jspdf

I am using html2canvas to take screenshot of my page and creating pdf of the images using jspdf. Now, my images are left aligned in the pdf document, I want it to be centered, how can I achieve it?
function pdfmaker() {
var element = $("#timesheet");
document.getElementById("message").style.display = "block";
document.getElementById("logo").style.display = "block";
var firstName = "<?php echo $fname?>";
var lastName = "<?php echo $lname ?>";
var startDate = "<?php echo $startDate?>";
var endDate = "<?php echo $endDate ?>";
html2canvas(element, {
useCORS: true,
onrendered: function(canvas) {
var imgData = canvas.toDataURL("image/png");
var imgWidth = 297; //297
var pageHeight = 297; //297
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
// var doc = new jsPDF('l', 'mm',[1350, 1350]);
var doc = new jsPDF('l', 'mm', [420, 297]); //420,297
var position = 5; //0
margins = {
top: 20,
bottom: 10,
left: 45,
width: 522
};
doc.addImage(imgData, 'PNG', 5, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 5) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 5, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save(firstName + '_' + lastName + '_Summary_report_' + startDate + '_' + endDate + ".pdf");
}
});
document.getElementById("message").style.display = "none";
document.getElementById("logo").style.display = "none";
}
You need to define inside the addImage() method, using the coordinate parameters, see: http://raw.githack.com/MrRio/jsPDF/master/docs/module-addImage.html
This is the only way you can do it. For this, I suggest you use the following method doc.internal.pageSize.getWidth(); to calculate the excess values ​​about the image width, which will be centered.

JSPDF : Genearte pdf from object of array and display like Lables

I want to generate PDF from object of array and display like this which I have attached in image. .how I can achieve this while my output is in row wise.
htmlStr += '<table id="customers" class="table-wide">';
htmlStr += '<thead ></thead>';
htmlStr += '<tbody ></tbodyid>';
htmlStr += '</table>';
this.html = $(htmlStr);
I think you have to do it on your own. jsPDF-Autotable is not good option for this scenario. Following is something like a scratch it's not a perfect solution. Please work on it further.
Actually we are going to create grid cards until the page width and height.
If height reaches, add new page doc.addPage().
If width reaches, add new row.
var data = [{
"Name": "Ronan",
"Email": "sodales.elit#eratSed.co.uk",
"Company": "Malesuada Malesuada Ltd"
}, {
"Name": "Calvin",
"Email": "amet.nulla#Vestibulumante.ca",
"Company": "Donec Egestas Foundation"
}, {
"Name": "Kane",
"Email": "Duis.mi#consectetueradipiscingelit.net",
"Company": "Arcu Institute"
}, {
"Name": "Kasper",
"Email": "magna.Phasellus.dolor#velconvallisin.co.uk",
"Company": "Tempor LLP"
}];
var doc = new jsPDF('p', 'pt', 'a4');
//Dimension of A4 in pts: 595 × 842
var pageWidth = 595;
var pageHeight = 842;
var pageMargin = 20;
pageWidth -= pageMargin * 2;
pageHeight -= pageMargin * 2;
var cellPadding = 10;
var cellWidth = 180;
var cellHeight = 70;
var lineHeight = 20;
var startX = pageMargin;
var startY = pageMargin;
doc.setFontSize(12);
var page = 1;
function createCard(item) {
//cell projection
var requiredWidth = startX + cellWidth + (cellPadding * 2);
var requiredHeight = startY + cellHeight + (cellPadding * 2);
if (requiredWidth <= pageWidth) {
textWriter(item, startX + cellPadding, startY + cellPadding);
startX = requiredWidth;
// startY += cellHeight + cellPadding;
} else {
if (requiredHeight > pageHeight) {
doc.addPage();
page++;
doc.setPage(page);
startY = pageMargin;
} else {
startY = requiredHeight;
}
startX = pageMargin;
textWriter(item, startX + cellPadding, startY + cellPadding);
startX = startX + cellWidth + (cellPadding * 2);
}
}
function textWriter(item, xAxis, yAxis) {
doc.text(item.Name, xAxis, yAxis);
doc.text(item.Email, xAxis, yAxis + lineHeight);
doc.text(item.Company, xAxis, yAxis + (lineHeight * 2));
}
for (var i = 0; i < data.length; i++) {
createCard(data[i]);
}
doc.save('grid.pdf');
For reference https://jsfiddle.net/Purushoth/jodfkz59/

Fixing the ios7 squished image in canvas, with rotation and scaling

I am having problems with images being squished in iOS7 using canvas. I have found the following post which seems to be headed in the right direction:
HTML5 Canvas drawImage ratio bug iOS
However, I am beyond the simple case of drawing an image, I am also rotating and scaling the context (for thumbnails with EXIF orientation data) before drawing the image. The code runs, but there is no image data in my thumbnails. I'm guessing this has to do with the canvas rotation and scaling. However, I'm having a hard time understanding why the thumbnail does not create properly when my squish factor is 1 (on an iOS device that does not have the bug).
Here is my full "onload()" code:
reader.onloadend = function(evt) {
console.log('read file data!');
var tempImg = new Image();
console.log('created new Image');
tempImg.src = evt.target.result;
console.log('set canvas to file');
// alert(this);
tempImg.onload = function() {
console.log('loaded tempImg');
var MAX_WIDTH = 450;
var MAX_HEIGHT = 450;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
// save the current co-ordinate system
// before we screw with it
ctx.save();
// move to the middle of where we want to draw our image
ctx.translate(tempW/2, tempH/2);
if (exifTags.hasOwnProperty('Orientation')) {
// EXIF FORMAT: 0x0112 Orientation int16u IFD0
// 1 = Horizontal (normal)
// 2 = Mirror horizontal
// 3 = Rotate 180
// 4 = Mirror vertical
// 5 = Mirror horizontal and rotate 270 CW
// 6 = Rotate 90 CW
// 7 = Mirror horizontal and rotate 90 CW
// 8 = Rotate 270 CW
// Working. See: http://creativejs.com/2012/01/day-10-drawing-rotated-images-into-canvas/
if (exifTags.Orientation == 2) {
console.log('orientation: 2 = Mirror horizontal')
// flip context horizontally
// ctx.translate
ctx.scale(-1, 1);
} else if (exifTags.Orientation == 3) {
console.log('orientation: 3 = Rotate 180')
ctx.rotate(180*Math.PI/180);
} else if (exifTags.Orientation == 4) {
console.log('orientation: 4 = Mirror vertical')
// flip context vertically
ctx.scale(1, -1);
} else if (exifTags.Orientation == 5) {
console.log('orientation: Mirror horizontal and rotate 270 CW')
// flip context horizontally
ctx.rotate(270*Math.PI/180);
ctx.scale(-1, 1);
} else if (exifTags.Orientation == 6) {
console.log('orientation: Rotate 90 CW')
ctx.rotate(90*Math.PI/180);
} else if (exifTags.Orientation == 7) {
console.log('orientation: Mirror horizontal and rotate 90 CW')
// flip context horizontally
ctx.rotate(90*Math.PI/180);
ctx.scale(-1, 1);
} else if (exifTags.Orientation == 8) {
console.log('orientation: Rotate 270 CW')
ctx.rotate(270*Math.PI/180);
} else {
console.log('unknown orientation: ' + exifTags.Orientation);
}
}
var myImage = this;
if ($scope.platform == "iOS") {
/* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into canvas for some images.
* This is a bug in iOS6 devices. This function from https://github.com/stomita/ios-imagefile-megapixel
*
*/
function detectVerticalSquash(img) {
var iw = img.naturalWidth, ih = img.naturalHeight;
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = ih;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, 1, ih).data;
// search image edge pixel position in case it is squashed vertically.
var sy = 0;
var ey = ih;
var py = ih;
while (py > sy) {
var alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
var ratio = (py / ih);
return (ratio===0)?1:ratio;
}
/**
* A replacement for context.drawImage
* (args are for source and destination).
*/
function drawImageIOSFix(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
var vertSquashRatio = detectVerticalSquash(img);
console.log('ratio: ' + vertSquashRatio);
// Works only if whole image is displayed:
// ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
// The following works correct also when only a part of the image is displayed:
ctx.drawImage(img, sx * vertSquashRatio, sy * vertSquashRatio,
sw * vertSquashRatio, sh * vertSquashRatio,
dx, dy, dw, dh );
}
console.log('image to unsquish', myImage);
// draw it up and to the left by half the width
// and height of the image
drawImageIOSFix(ctx, myImage, -tempW/2, -tempH/2, tempW, tempH);
} else {
// draw it up and to the left by half the width
// and height of the image
ctx.drawImage(myImage, -tempW/2, -tempH/2, tempW, tempH);
}
// and restore the co-ords to how they were when we began
ctx.restore();
var dataURL = canvas.toDataURL();
// alert('created image!');
var fileName = undefined;
if ($scope.platform == "iOS") {
// Store only the name for iOS, hard paths are unreliable
var timestamp = new Date().getTime();
fileName = timestamp.toString().concat('t.jpg');
var thumbPath = fileSystem.root.toURL() + "/STL/" + fileName;
var thumbName = "/STL/" + fileName;
} else {
var name = file.name
var position = name.length-4
fileName = name.substr(0, position) + 't.jpg';
var thumbPath = fileSystem.root.toURL() + "/.STL/" + thumbName;
var thumbName = fileName;
}
$scope.mediaCollection.thumbNames.push(thumbName);
$scope.mediaCollection.thumbPaths.push(thumbPath);
$scope.mediaCollection.exifData.push(exifTags);
$scope.mediaCollection.Orientation.push(exifTags.Orientation);
canvas.toBlob(function(blob){
console.log(blob.size + ':' + blob.type);
function newFile(fileEntry){
console.log('created new fileEntry');
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
console.log('got fileWriter');
writer.seek(0);
// window.location = blobUrl;
writer.write(blob);
console.log('wrote blob!');
writeIfReady();
}
console.log('about to get Directory');
console.log('fileSystem root: ', fileSystem.root, $scope.iOS_FS);
console.log('platform: ', $scope.platform);
// can replace if/else with single request using $scope.STL_dir
if ($scope.platform = "iOS") {
// May need maintenance...
fileSystem.root.getDirectory('STL', {create: true}, function(dirEntry) {
console.log('got directory, about to create thumbnail file: ' + fileName);
dirEntry.getFile(fileName, {create: true, exclusive: true}, newFile, fail);
}, fail);
} else {
fileSystem.root.getDirectory('.STL', {create: true}, function(dirEntry) {
dirEntry.getFile(fileName, {create: true, exclusive: true}, newFile, fail);
}, fail);
}
}, "image/jpg");
}
}

Resources