Google Chrome extension margin/blank space insert for image - javascript

I'm designing a Google Chrome extension. It is designed to insert an image into text. It currently does so, but the image attached at the bottom shows my problem. The image displays over text, and I was wondering if there was a way to make the image have its own separate space, as if I was using margin - so the snake is to the left of the logo and all of the links, and everything else on the page is shifted to the right slightly. Neither marginLeft nor marginRight work, though. This is my code:
popup.js:
function imageappend() {
const img = document.createElement("img");
img.src = chrome.runtime.getURL("imageedit_1_3932659157.png");
img.style.position = "fixed";
img.style.top = "0";
img.style.left = "0";
img.style.padding = "0";
img.style.marginRight = "7%";
img.style.marginLeft = "0";
img.style.marginBottom = "0";
img.style.marginTop = "0";
img.style.width = "5%";
document.body.appendChild(img);
}
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: imageappend
});
})();

There is not easy answer. It depends much by the layout of the document you inject your script into. The script is injected in the main frame or in a specific one?
If we take as model the wiki page (which it'd seems it have not frameset) you could move all body content in a new div styled with float:right and insert your image in another div (at the same level of the previous div) styling it with float:left
Something like this:
<body>
<div id="csImg" style="float:left"> <img src="..." style="..."> <div>
<div id="mainContainer" style="position:relative; float:right"> all moved body content <div>
<body>
There are several ways to do the same thing... ... and I'm certainly not a black belt in CSS.
Note that if you style the injected image with:
position:fixed
top:"0"
left:"0"
you'll always get an overlaid image placed in the upper left corner of the document.

Related

Adobe Creative SDK web displaying a small image after load

I'm integrating Adobe Creative SDK WEB to my angularjs website.
I have followed the "Image Editor UI" guide from official Adobe website
And also a this example using angularjs:
https:// github.com/CreativeSDK/web-getting-started-samples/tree/master/image-editor-ui/image-editor-ui-angular-express>
In both cases I tried with dynamic and hard coded id and image src.
** This is working **
When I click the "edit" link, editor opens fine and start loading the image.
While loading, the image size is exactly the same as my placeholder size.
Screen capture of my table with image and link https://ibb.co/kZ5ama
** End this is working **
The problem I'm getting is this:
After the photo is loaded, the size shrinks and goes to the top left corner.
Also when I try to draw on top of it, I have to start by clicking inside the small photo and continue as if the size of the photo is the entire screen.
Screen capture of the editor here, look at the end of the red stroke and my cursor position: https://ibb.co/iYJECF
Here is my edit link
<a href="javascript:;" id="edit-image-button" class="btn btn-primary btn-block button-panel" ng-click="launchEditor('image_'+$index, item2)">
Edit Image
</a>
My image placeholder
<a ng-click="openLightboxModal(name2,'notsynced')" >
<img id="image_{{$index}}"class="img-responsive" src="{{item2}}" alt="">
</a>
$scope.getImageEditor = function() {
$scope.imageEditor = new Aviary.Feather({
apiKey: "My id is here",
onSave: function(imageID, newURL) {
$scope.currentImageSrc = newURL;
$scope.imageEditor.close();
$scope.$digest();
console.log(newURL);
},
onError: function(errorObj) {
console.log(errorObj.code);
console.log(errorObj.message);
console.log(errorObj.args);
}
});
}
$scope.launchEditor = function(imageId, imageURL) {
$scope.originalImageSrc = imageURL;
$scope.currentImageSrc = $scope.originalImageSrc;
console.log(imageId);
console.log(imageURL);
$scope.imageId = imageId;
var terms = /^https?:///;
var isUrl = $scope.currentImageSrc.match(terms);
if (isUrl) {
$scope.imageEditor.launch({
image: $scope.imageId,
url: $scope.currentImageSrc
});
}
else {
$scope.imageEditor.launch({
image: $scope.imageId
});
}
}
After removing all CSS and inspecting element by element, I have found the culprit. It was a CSS conflict, which made all CANVAS element to have a fixed height of 100px.
Thanks for reading.

JS: Stretching mediaelement to fit page and getting rid of thin border

The below is part of a script that loads two mediaelements with cams on a smartphone screen for two parties in a chat: A small view of oneself, and a big one supposed to fill the whole screen with the remote party. There are two things I would like to modify:
There´s a thin border around the element. I want to get rid of that.
The other problem is that the remote view doesn´t fill out the whole screen in the height. Could someone help me to succeed with these two issues? Thanks in advance:
connection.videosContainer = document.getElementById('videos-container');
connection.onstream = function(event) {
var width = parseInt(connection.videosContainer.clientWidth);
if (event.type === 'remote') {
var mediaElement = getMediaElement(event.mediaElement, {
title: event.userid,
buttons: [],
width: width,
showOnMouseEnter: false
});
mediaElement.style.height = "100%";
mediaElement.style.width = "100%";
mediaElement.style.zIndex = "1";
mediaElement.style.position = 'absolute';
mediaElement.style.top = 0;
mediaElement.style.left = 0;
document.getElementById("videos-container").appendChild(mediaElement);
}

Turning HTML content in to a canvas element [duplicate]

It would be incredibly useful to be able to temporarily convert a regular element into a canvas. For example, say I have a styled div that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement into the canvas, hide the original element and animate the canvas.
Can it be done?
There is a library that try to do what you say.
See this examples and get the code
http://hertzen.com/experiments/jsfeedback/
http://html2canvas.hertzen.com/
Reads the DOM, from the html and render it to a canvas, fail on some, but in general works.
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Its key trick was:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like ' +
'<span style="color:white; text-shadow:0 0 2px blue;">' +
'cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
That is, it used a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details — basically it's a lot more limited than an iframe or AJAX due to privacy and cross-domain concerns.)
Sorry, the browser won't render HTML into a canvas.
It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.
To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage and fillText, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle and relative positions of parts of it using offsetTop et al.)
You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:
var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(img, 0, 0);
parent.removeChild(node);
parent.appendChild(canvas);
};
img.src = pngDataUrl;
});
And here is jsfiddle
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
No such thing, sorry.
Though the spec states:
A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.
Which may be as close as you'll get.
A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.
The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.
You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.
this code work with the library: https://github.com/tsayen/dom-to-image
*the "id_div" is the id of the element html that you want to transform.
**the "canvas_out" is the id of the div that will contain the canvas
so try this code.
:
function Guardardiv(id_div){
var mode = 2 // default 1 (save to image), mode 2 = save to canvas
console.log("Process start");
var node = document.getElementById(id_div);
// get the div that will contain the canvas
var canvas_out = document.getElementById('canvas_out');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
};
if (mode == 1){ // save to image
downloadURI(pngDataUrl, "salida.png");
}else if (mode == 2){ // save to canvas
img.src = pngDataUrl;
canvas_out.appendChild(img);
}
console.log("Process finish");
});
}
so, if you want to save to image just add this function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
}
Example of use:
<html>
<head>
</script src="/dom-to-image.js"></script>
</head>
<body>
<div id="container">
All content that want to transform
</div>
<button onclick="Guardardiv('container');">Convert<button>
<!-- if use mode 2 -->
<div id="canvas_out"></div>
</html>
Comment if that work.
Comenten si les sirvio :)
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
function convert() {
dom = document.getElementById('divname');
var script,
$this = this,
options = this.options,
runH2c = function(){
try {
var canvas = window.html2canvas([ document.getElementById('divname') ], {
onrendered: function( canvas ) {
window.open(canvas.toDataURL());
}
});
} catch( e ) {
$this.h2cDone = true;
log("Error in html2canvas: " + e.message);
}
};
if ( window.html2canvas === undefined && script === undefined ) {
} else {.
// html2canvas already loaded, just run it then
runH2c();
}
}

Images added to div are not affected by the scrollbar

I have an empty div with a scrollbar:
<div id="figure1" style="width:1000px; height:300px; overflow:scroll;"></div>
And using javascript I am adding images into the div:
function add_img(imgID, src, x, y, height, width){
var img = document.createElement("img");
img.setAttribute('id', imgID);
img.setAttribute('src', src);
img.style.left = x;
img.style.top = y;
img.style.width = width;
img.style.height = height;
img.style.position = 'absolute';
document.getElementById('figure1').appendChild(img);
}
When I add a new image outside of the 1000x300px box, I want that image to only be visible when you use the scrollbar.
Instead, the images which lie outside of the box overflow beyond the edges of figure1. The scrollbar doesn't do anything.
How can I stop the images from overflowing?
Thanks!
I see two issue - first you need to add + "px" to your dimensions (at least if you use integer type parameters like I did).
The other thing would be not to use position = "absolute". For example position = "relative" seems to do the trick. (If you like, have a further read on the layout options in CSS, good luck)
https://jsfiddle.net/xpsu9usw/

JQuery: How to hide an image until source changed

I have an image that is being resized programmatically, based on the current height/width of the container. My problem is that it shows the image at it's original size before it does the resizing.
See this JSFiddle
You'll notice how it flashes up a stretched image before it fits the image nicely in the middle.
I want to hide the image until that resizing has taken place, but I can't figure out how.
Any suggestions?
JSCode:
function LoadImg(img) {
img.css('visibility','hidden');
var src=img.attr('src');
var imgh = img.parent().height();
var imgw = img.parent().width();
var pattern = /&?(w|h)=[^&]+/g;
src = src.replace(pattern, '');
img.attr('src', src + '&w=' + imgw + '&h=' + imgh);
img.css('visibility','');
}
Html:
<div class="window">
<img src="http://www.angclassiccarparts.co.uk/image_anysize.aspx?f=/images/ww/panel/service_kits.jpg&w=154&h=154&color=png" id="img" onload="LoadImg($(this));" />
</div>
I've tried hiding with visibility hidden until the function has run, but that doesn't wait for it to load...
You're changing the source of the image, which forces it to load a new image, then you instantly set the image to visible.
Ultimately you want to wait until the second image is loaded before showing it, which can be achieved using .load() like so:
img.on('load', function() {
img.css('visibility','visible');
});
Here's an updated jsFiddle with the working code: http://jsfiddle.net/ev4YL/2/
I would, however, recommend a different approach. It doesn't make much sense to load an image, then when it's loaded load another image. Perhaps you should store the dimensions in html data attributes, then load the images dynamically on document.ready.
Something like this could work, if you set each image to have a data-src instead of src to begin with:
$('img').each(function() {
var img = $(this);
var src = img.attr('data-src');
var imgh = img.parent().height();
var imgw = img.parent().width();
var pattern = /&?(w|h)=[^&]+/g;
src = src.replace(pattern, '');
img.attr('src', src + '&w=' + imgw + '&h=' + imgh);
img.on('load', function() {
img.css('visibility','visible');
});
});
And the demo here: http://jsfiddle.net/ev4YL/4/
You can hide the image with display: none until the end of the function, then set the image to display: block (or whatever you need) at the very end. That way the rest of the function has already run, when it displays it will have already been resized.
See JSFiddle
But basically just:
CSS:
img {
display: none;
}
JavaScript:
function loadImg(img) {
----all of your function here----
img.css('display', 'block');
}

Categories