angular 6 convert html to image - angular6

I want to convert my HTML element to png. So I'm using the html-to-image package to do this. I'm getting a blank image when I'm converting. Here is my code
<div #myDiv id="content" [innerHTML]="tempInnerHtml"></div>
<img [src]="snapshot">
this.tempInnerHtml = this.sanitizer.bypassSecurityTrustHtml(this.tempValue);
var node = document.getElementById('content');
htmlToImage.toPng(node)
.then((dataUrl) => {
console.log(dataUrl);
this.snapshot = dataUrl;
}).catch((error) => {
console.error('oops, something went wrong!', error);
});
My inner HTML loads without any problem but the output image is always a blank image. Can anyone help me to solve this? Thank you.

Related

Playwright; asserting nested `img src` values

Note, this is related to my previous question here: https://stackoverflow.com/a/73043433/4190664
I am looking to further assert somethings within the DOM when I click the 'Print' button.
From troubleshooting I am seeing the following:
the pdfjs page has a #printContainer that is an empty div
when you click the Print button, it begins creating divs with the class .printedPage to represent each page of the document
within each .printedPage div is an img element with src="blob:https://mozilla.github.io/**"
Example when the print dialog is open:
<div id="printContainer">
<div class="printedPage"><img src="blob:https://mozilla.github.io/5afcff4c-aa36-4118-b4b8-011cdce6a9bc"></div>
<div class="printedPage"><img src="blob:https://mozilla.github.io/30cd3036-2d81-4b82-af9a-0f2e9c834b69"></div>
<div class="printedPage"><img src="blob:https://mozilla.github.io/047e8762-3fae-44d1-a5a0-56ea576de93e"></div>
</div>
I already am testing the following:
let requestCount = 0;
page.on('request', request => {
if(request.url().includes('blob:https://mozilla.github.io/pdf.js/web/viewer.html')) {
expect(page.locator(`.printedPage img >> nth=${requestCount}`)).toHaveAttribute('src', /blob:https:\/\/mozilla.github.io/);
requestCount++;
}
});
await printBtn.click();
await expect.poll(() => requestCount).toBe(3);
What would be the best way to assert that each .printedPage > 'img' src contains the blob information as well?
Playwright (and javascript in general) is not a strong language so I am definitely struggling on this one 😬
Any syntactical help is appreciated
You can do something like this. You can add this before the value of requestCount increments.
await expect(
page.locator(`.printedPage img >> nth=${requestCount}`)
).toHaveAttribute('src', /blob:https:\/\/mozilla.github.io/)

How to render an element in React which was created by createElement()?

I have created an image element by using:
const image = document.createElement('image'); // or new Image();
How can I render this image variable in React ?
I don't want to use Html tags to do something like this:
<img src={image.src} ... />
Is there any other way ?
Well either create a <div class="parent"> </div> and then use
document.querySelector(".parent").appendChild(imageElement)
or simply,
document.appendChild(imageElement)
This is the wrong way to go about doing this. You shouldn't directly manipulate the DOM with React. I would instead have an array of objects in your state, and in your component, map the objects to the elements of your choosing. Like this
const Component = () => {
const [components, setComponents] = useState([{src:'path/to/src', alt:'altTag'}])
return(
<>
{
components.map(e => {
return(<img src={require(e.src)} alt={e.alt} />)
})
}
</>
)
}
Wrote this from memory/without testing so there might be something wrong so dont kill me. But if you need to render it anywhere, make it its own component. If it's truly just one image, then you don't need the array/map just use an object and render it same way

iOS - Safari - images not rendering fully / cut off

We are loading images in a popup, via an Ajax request, and they intermittently only partially render.
I've basically removed any weird Javascript/nonsense other than the core flow - just a basic HTML image, and it is still happening - only on iOS.
Once you 'rotate' the device, the image renders correctly - so, it's not a weird div floating above or anything (I can select the image in iOS debugger mode when attached to a Mac)
Any help would be most appreciated.
Setting decoding="sync" on the img tag didn't help in my case where a lot of images are loaded simultaneously. Loading the image manually before did the trick though.
const imageLoader = new Image();
imageLoader.src = url;
imageLoader.decoding = 'sync';
imageLoader.onload = () => {
// allow drawing image
};
For anyone who stumbles across this and is working in a react environment
const [didLoadMainImage, setDidLoadMainImage] = useState(false);
useMemo(() => {
setDidLoadMainImage(false);
const imageLoader = new Image();
imageLoader.src = url;
imageLoader.decoding = 'sync';
imageLoader.onload = () => {
setDidLoadMainImage(true);
};
}, [url]);
return (
<div>
{didLoadMainImage ? (
<img src={url} />
) : null}
</div>
);
It seems this is an issue within the iOS image decoder - some kind of race condition.
This has been fixed by forcing the decoder to operate on the main thread, using:
<img decoding="sync" src="#Url" />
Hopefully this helps someone else!
In my case, the solution was to decrease the size of the images I was displaying. Our images were about 10x the size of the HTML element they were displayed in.
Apple's developer document states:

How to display openweathermap weather icon

I am using openweathermap to display weather reports. Everything is working fine but there is a problem with the icon.
The JSON response code is:
Array
(
[city] => Array
(
[id] => 1271476
[name] => Guwahati
[coord] => Array
(
[lon] => 91.751
[lat] => 26.1862
)
[country] => IN
[population] => 899094
)
[cod] => 200
[message] => 0.0630711
[cnt] => 1
[list] => Array
(
[0] => Array
(
[dt] => 1495688400
[temp] => Array
(
[day] => 33
[min] => 24.89
[max] => 33.82
[night] => 24.89
[eve] => 30.6
[morn] => 33
)
[pressure] => 1013.02
[humidity] => 90
[weather] => Array
(
[0] => Array
(
[id] => 500
[main] => Rain
[description] => light rain
[icon] => 10d
)
)
[speed] => 3.92
[deg] => 88
[clouds] => 24
[rain] => 2.73
)
)
)
Now how can I display the icon: [weather][0][icon] => 10d?
What is 10d & how can I get the URL of the icon?
Well, I know a way using jQuery.
<div id="icon"><img id="wicon" src="" alt="Weather icon"></div>
At the HTML above you see the unique thing missing is the src attribute, so let's fill it with some jQuery and JavaScript.
You may create a variable to hold the icon code provided by the API like:
var iconcode = a.weather[0].icon;
After it you should concatenate this var iconcode with the url that contains the icons, like:
var iconurl = "http://openweathermap.org/img/w/" + iconcode + ".png";
Finally just change src attribute in the DOM by doing this:
$('#wicon').attr('src', iconurl);
You can get OpenWeatherMap API icons through this link. All you need to do is that moderate the icon id given in bold below in this link. You can change 10d with any icon id that you need.
http://openweathermap.org/img/w/10d.png
For more information, You can read here OpenWeatherMap Icons
So I spent a lot of time solving this problem. This answer is for pure HTML and JavaScript and if you don't want to use jquery.
1- Include the "icons" file in your program: openweatherAPI Icons integration
2- In your index.html :
<div class="weather-icon"><img src="icons/unknown.png" /></div>
3- In your JavScript file(follow these 3 steps in your JS code) :
1st Step: let locationIcon = document.querySelector('.weather-icon');
2nd Step: const {icon} = data.weather[0];
3rd Step(not in code format, as it was making thebackticks part disappear):
locationIcon.innerHTML = <img src="icons/${icon}.png">;
Worked just fine for me.
Happy building.
the src of the icon would be like this:
http://openweathermap.org/img/wn/10d#2x.png
see Weather icons
This code works for me in React Native:
const icon = wInfo.weather[0].icon; // For instance "09d"
<Image source={{ uri: ``http://openweathermap.org/img/w/${icon}.png`` }} />
Thank you all very much! I am a very beginning Flutter programmer and wanted to display the Icon in the Weatherapp, we made on course with Angela Yu.
I did this in Flutter:
String weerImageString;
weerImageString = weatherData['weather'][0]['icon'];
and then were I wanted it to display, I did:
Image.network('http://openweathermap.org/img/w/$weerImageString.png',),
I hope that I can someday helping someone with this. And... if there is an easier way, I would love to hear!
For react, you can use like this:
Step 1: initialize blank state
constructor(){
super()
this.state={
icon:''
}
}
Step 2: api call
async componentDidMount(){
const url = 'http://api.openweathermap.org/data/2.5/'
const key = 'your api key'
const response = await fetch(`${url}weather?q=Guwahati&units=metric&APPID=${key}`)
const data = await response.json() //this will return the json response
const iconName = data.weather[0].icon // this will hold the icon
const iconApi = await fetch('http://openweathermap.org/img/w/' + iconName + '.png')
this.setState({
icon : iconApi.url
})
}
Step 3: Display icon
<div className="weather-icon">
<img style={{width:'70px'}} src= {this.state.icon} />
</div>
Here d refers to day, like n refers to night.
And based on weather status it will change, e.g. 03d for scattered clouds, 01d for clear sky etc.
Here you will get a full list of these icons https://openweathermap.org/weather-conditions#How-to-get-icon-URL
This answer is in reference to the Android,
so after struggling for few hours I finally figured out how to display icons from openweathermap api.
The URL is https://openweathermap.org/img/w/${icon_id}.png
Just put the icon Id you are getting from the API and you will get the result.
Common mistakes which I faced were :
Not using https, as I was using http and it was not working
Also you can get bigger size image by using :
url - https://openweathermap.org/img/wn/${icon_id}#4x.png
icon_id examples : 04d, 10d
working response : https://openweathermap.org/img/wn/04d#4x.png
This is how i solved it. Totally works. no need for JQuery or any of those.
First thing is you realize that the api route is in an array in the weather tab so u have to parse it correctly. use console.log to make sure the get the "10n" kind of result so u know you are getting the right output.
then you use this img tag
<img
alt="icon"
src={http://openweathermap.org/img/w/${icon}.png}
width="120"
height="100"
/>
where icon is the string "04n" that you get from the parsed data.
then it should work perfectly.
Below is my parsed data example. you can see i am geting the temp, humidity, dt_txt is one of the results and icon is the icon
(
{ main: { temp, humidity }, dt_txt, weather: [{ icon }] },
index
)
Firstly, 10d is the icon id that changes according to the forecast data.
I was doing a react weather-App project, and I did the following in my component:
<div>
<img
id="wicon"
src={`http://openweathermap.org/img/wn/${a.weather[0].icon}#2x.png`}
alt="weather icon">
</img>
</div>
This way if the value of the icon change it automatically changes in the Dom.
This worked for me!
create variable to access data between javascript and HTML.
var var1 = document.querySelector('idhere') // you have to use parent class/id
Get icon from JASON
var tempvariable = data['weather'][0]['icon'];
pass link along with html tag to html
var1.innerHTML = "http://openweathermap.org/img/w/" +tempvariable+ ".png' alt='Icon depicting current weather.'>"
or
var1.innerHTML = "http://openweathermap.org/img/w/" +data['weather'][0]['icon']+ ".png' alt='Icon depicting current weather.'>"// step 2 is not required if you use this method.
http://openweathermap.org/img/wn/$weatherData.weather[0].icon#2x.png
To display this on a webpage, you could just add it to the src attribute of an img tag.
This is what the URL for getting the icon will look like....
Where weatherData is the data that you get from the API call you make to the OPENWEATHERMAP. It comes in JSON format. You need to parse.
I think you are asking about IconCode
https://openweathermap.org/
to get converted to an image
For example 02n =>img
So, if thats what you want, then:
You need to use this link
https://openweathermap.org/img/wn/02n#2x.png
Replace the '02n' with the image codes you get as a response
Done
For more image codes information Go to link
const icon = `https://openweathermap.org/img/wn/${weather[0]["icon"]}#2x.png`;
const li = document.createElement("li");
li.classList.add("city");
const markup = `
<figure>
<img class="city-icon" src=${icon} alt=${weather[0]["main"]}>
<figcaption>${weather[0]["description"]}</figcaption>
</figure>
`;
li.innerHTML = markup;
This is what I did and it worked for me. You see, from the response object map through it and with the result access icon as follows
<img src="http://openweathermap.org/img/w/${result.icon}.png" alt="img">
Your html file:
<div class="weather">
<form class="weather-form">
<input type="text" class="city-name">
<input type="submit">
</form>
<img src="" class="iconurl">
</div>
Your JS file:
// hit API
const getWeather = async (cityname) => {
let response = await fetch('https://api.openweathermap.org/data/2.5/weather?q=' + cityname + '&appid=${API KEY}') //you get your api key once you sign up for openweathermap.org
return response.json()
}
// DOM
const weatherContainer = document.querySelector('.weather')
const weatherForm = document.querySelector('.weather-form')
const iconurl = document.querySelector('.iconurl')
// Event Listener
weatherForm.addEventListener('submit', (e) => {
e.preventDefault()
const cityInput = document.querySelector('.city-name')
getWeather(cityInput.value).then(c => {
c.weather.forEach(ww => {
let url = "http://openweathermap.org/img/w/" + ww.icon + ".png"
iconurl.src = url
})
})
})
I had a same problem in Flutter/Dart but not only can't display weather icon but also icon string doesn't have a "http:" in response. I'm working on weatherapi.com.
Here's how You do it in FLUTTER/DART and I'm using Dio package(not http):
In model that You build You need to add:
icon_url = "http:" + json['current']['condition']['icon'] - I did it with "http:" first cause as I said, response doesn't have it in icon url, otherwise just use rest of the code if You're using openweathermap, parameters in [] are just parameters from response, change them, depended on your API. To display icon use Image.network(
nameofyourModel.icon_url). Hope it helps somebody !
ExpressJS:
First Get Icon:
const icon = weather.weather[0].icon;
Second:
iconurl= http://openweathermap.org/img/wn/${icon}.png;
Third:
" alt="">
A little late I must admit. I'm at University right now and I had the same experience as you, where I didn't know how to get the icon to work.
However, a guy at University was kind enough to give me help, which I appreciate very much.
So, in your Javascript, you put:
document.getElementById("icon").src = "https://openweathermap.org/img/wn/" + response.weather[0].icon + "#2x.png";
And in your HTML, you put:
<img id="icon" src = "" alt = "Weather icon">
Hope this helps anyone who was in the same situation as me :)
Thanks!

chrome extension: Parse JSON data and get image

i have a json data like that
{ "ikealogo": "https://xxx.blob.core.windows.net/logo/24536.jpg?v=20120912144845" }
how can i convert it in image view?
Things i have tried but need alternate solution. it works fine in popup window but **i need to convert it for my content script in a specific webpage, when user will hover mouse on a text and should appear this image ** but applying same process is not working at all.
//popup.js
var image = document.getElementById('img');
image.src = jsonData.ikea.ikealogo;
//popup.html
<img id="img" />
SOLUTION:
To appear any image from external server on DOM :
I parse data from API response and create div with jquery and append the image data inside it.
There's NO need for CROSS DOMAIN COMPLICITY.
var image= data["company"].ikealogo;
var div=jQuery('<div/>',
{
"class": "divC",
});
var i = jQuery('<img />').error(function()
{
this.src = default_image;
}).attr('src', image)
.css({ "width":"50px", "height": "50px","margin": "0px 10px 10px 10px"});
div.append(i)