Using css-background image with img element - javascript

Is it possible to load image data stored in img element into a css background-image property?
For example, assume that we have downloaded image data into 'img' element
var img = Image();
img.src = '/foo/bar'
img.onload = ....
Then, I'd like to load that image to the css background-image property
.something {
background-image: img
}
Is this possible? Mixing using image Element and css background-image property so that CSS can use image data in img element as a background-image

Edit: This first answer was only ever meant to address the original question asked around working with an image element. Scroll down for a better alternative to fetching image data.
If you are trying to safely capture the raw data to use at a later point, you can draw the image onto a canvas element in order to generate a base-64 encoded data-URL. Though this solution will be subject to same-origin restrictions.
see: MDN: Allowing cross-origin use of images and canvas
const getImageData = imageElement => {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = imageElement.width
canvas.height = imageElement.height
ctx.drawImage(imageElement, 0, 0)
return canvas.toDataURL()
}
const img = new Image
img.addEventListener('load', () =>
// assign to some CSS rule
console.log(getImageData(img))
)
img.src = '/foo/bar'
Reading between the lines however your comment, "wouldn't that make the browser download the image twice?" sounds like a misunderstanding - browsers already cache resources and you can reuse asset URLs in any context in your page (i.e. HTML / CSS / JS) and unless explicitly circumvented, rely on them only being downloaded once.
Alternatively, it would be cleaner to load the image as a Blob.
Note: I'm using a CORS proxy here purely to facilitate a runnable example. You probably wouldn't want to pass your own assets through an arbitrary third-party in a production environment.
see: MDN: Cross-Origin Resource Sharing
const getImage = async url => {
const proxy = 'https://cors-anywhere.herokuapp.com/'
const response = await fetch(`${proxy}${url}`)
const blob = await response.blob()
return URL.createObjectURL(blob)
}
const imageUrl =
'https://cdn.sstatic.net/Sites/stackoverflow/' +
'company/img/logos/so/so-logo.png?v=9c558ec15d8a'
const example = document.querySelector('.example')
getImage(imageUrl).then(objectUrl =>
example.style.backgroundImage = `url(${objectUrl})`
)
.example {
min-height: 140px;
background-size: contain;
background-repeat: no-repeat;
}
<div class="example"></div>

You can do this with JQuery
var img = new Image();
img.src = 'http://placehold.it/350x150';
$('div').css('background-image', 'url('+img.src+')');
div {
height: 150px;
width: 300px;
background-size: cover;
background-position: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Or pure Javascript
var img = new Image();
img.src = 'http://placehold.it/350x150';
document.getElementById('element').style.backgroundImage = "url("+img.src+")";
div {
height: 150px;
width: 300px;
background-size: cover;
background-position: center;
}
<div id="element"></div>

Related

Get image width and height. src is proxy

I have a Vue component, in it I have an img, I need to get that image dimensions, preferably before showing the image (to fit in the container either by width or height).
this.img = new Image();
this.img.src = this.payload.src;
this.img.onload = () => {
let width = this.img.naturalWidth;
let height = this.img.naturalHeight;
}
That code might not work, the image src can return 401 (not sure yet), we use proxy and get that file from a storage bucket on the server. like /api/getStorageResource?blob=
What can I do?
Having the link, can I somehow fetch image through axios and set it as an element, instead of <img src=".." />
As an option I see that I can probably have the element as it is now <img src="/api/getStorageResource?blob=" /> and getElementById it and get the width and height... Not sure what my options here.
You can use a combination of async/await and the fetch api inside a try/catch block to get the image URL from your server and then you can proceed with creating the <img> element, assign the retrieved image URL to the img element src and finally set the width and height of the container equal to the img element's width and height.
In the following example Code Snippet, I have added a button which will add the image to the container on click so you can see how the container has the retrieved image dimensions even before the image is rendered on the DOM:
const imgDiv = document.querySelector('#imgDiv');
const btn = document.querySelector('#imgBtn');
//The fetchImg function will fetch the image URL from the server and log error to console if file not found
const fetchImg = async () => {
try {
// replace the following example url with "this.payload.src"
const imgURL = await fetch('https://picsum.photos/id/237/200/200');
return imgURL;
} catch (err) {
// do something here if image not found
console.log('Image not found!');
}
}
fetchImg().then((res) => {
// create a new image element with the URL as the src
const img = new Image();
img.src = res.url; // change ".url" according to how the data you get from your server is structured
// assign the retrieved width and height of img to container
img.addEventListener('load', () => {
imgDiv.style.width = img.naturalWidth + 'px';
imgDiv.style.height = img.naturalHeight + 'px';
});
btn.addEventListener('click', () => imgDiv.appendChild(img));
});
html, body {margin: 0;padding: 10px;width: 100%; height: 100%;text-align: center;}
#imgDiv {background-color: #222;margin: 0 auto;}
<button id="imgBtn">Add Image</button>
<div id="imgDiv"></div>
JSFiddle with above code: https://jsfiddle.net/AndrewL64/2hu3yxtq/104/

Render background-image to canvas

I have a DIV container with an image set as background-image (specified by url). Is there any way how to redraw this background-image into canvas (without re-contacting or re-downloading from server -- as the content image is once-to-show)?
Yes. You can get the URL of the background image, request the image file as Blob, create an <img> element, set src to Blob URL of response, at load event of created img element call .drawImage() with img as first parameter.
The background image could be cached, depending on browser settings. If the image is not cached at browser, you can request image first, then set both css background-image and <canvas> using single request.
You can use fetch() or XMLHttpResponse() to request background-image url(), FileReader(), FileReader.prototype.readAsDataURL() to set src of <img> to .result of FileReader at load event.
You can also use URL.createObjectURL() to create a Blob URL from response Blob. URL.revokeObjectURL() to revoke the Blob URL.
Check Network tab at DevTools or Developer Tools, the image should be retrieved
(from cache)
#bg {
width:50px;
height:50px;
background-image:url(http://placehold.it/50x50);
}
<div id="bg"></div>
<br>
<canvas id="canvas" width="50px" height="50px"></canvas>
<script>
window.onload = function() {
var bg = document.getElementById("bg");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image;
img.width = canvas.width;
img.height = canvas.height;
img.onload = (e) => ctx.drawImage(e.target,0,0);
var background = getComputedStyle(bg).getPropertyValue("background-image");
var src = background.replace(/^url|["()]/g, "");
var reader = new FileReader;
reader.onload = (e) => img.src = e.target.result;
fetch(src)
.then(response => response.blob())
.then(blob => {
reader.readAsDataURL(blob);
// const url = URL.createObjectURL(blob); img.src = url;
})
}
</script>

Convert SVG dataUrl to base64

I'm using a plugin (dom-to-image) to generate a SVG content from a div.
It returns me a dataURL like this:
data image/xml, charset utf-8, <svg...
If a put this on a <img src the image is shown to normally.
The intent is to grab this dataURL, convert it to base64 so I can save it as an image.png on a mobile app.
Is it possible?
I tryied this solution https://stackoverflow.com/a/28450879/1691609
But coudn't get to work.
The console fire an error about the dataUrl
TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'.
==== UPDATE :: PROBLEM EXPLANATION/HISTORY ====
I'm using Ionic Framework, so my project is an mobile app.
The dom-to-image is already working cause right now, its rendering a PNG through toPng function.
The problem is the raster PNG is a blurry.
So I thought: Maybe the SVG will have better quality.
And it IS!! Its 100% perfect, actually.
On Ionic, I'm using 2 step procedure to save the image.
After get the PNG generated by the dom-to-img(base64) dataURL, I convert it to a Blob and then save into device.
This is working, but the final result, as I said, is blurry.
Then with SVG maybe it will be more "high quality" per say.
So, in order to do "minimal" change on a process that s already working :D I just need to convert an SVG into base64 dataURL....
Or, as some of you explained to me, into something else, like canvas...
I don't know any much :/
===
Sorry for the long post, and I really, really thank your help guys!!
EDIT COUPLE OF YARS LATER
Use JS fiddle for a working example: https://jsfiddle.net/msb42ojx/
Note, if you don't own DOM content (images), and those images don't have CORS enabled for everyone (Access-Control-Allow-Origin header), canvas cant render those images
I'm not trying to find out why is your case not working, here is how I did when I had something similar to do:
get the image sourcce (dom-to-image result)
set up a canvas with that image inside (using the image source)
download the image from canvas in whatever image you like: png, jpeg whatever
by the way you can resize the image to a standard format
document.getElementById('mydownload').onclick= function(){
var wrapper = document.getElementById('wrapper');
//dom to image
domtoimage.toSvg(wrapper).then(function (svgDataUrl) {
//download function
downloadPNGFromAnyImageSrc(svgDataUrl);
});
}
function downloadPNGFromAnyImageSrc(src)
{
//recreate the image with src recieved
var img = new Image;
//when image loaded (to know width and height)
img.onload = function(){
//drow image inside a canvas
var canvas = convertImageToCanvas(img);
//get image/png from convas
var pngImage = convertCanvasToImage(canvas);
//download
var anchor = document.createElement('a');
anchor.setAttribute('href', pngImage.src);
anchor.setAttribute('download', 'image.png');
anchor.click();
};
img.src = src;
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
// Converts canvas to an image
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
}
#wrapper{
background: red;
color: blue;
}
<script src="https://rawgit.com/tsayen/dom-to-image/master/src/dom-to-image.js"></script>
<button id='mydownload'>Download DomToImage</button>
<div id="wrapper">
<img src="http://i.imgur.com/6GvKdxY.jpg"/>
<div> DUDE IS WORKING</div>
<img src="http://i.imgur.com/6GvKdxY.jpg"/>
</div>
I translated #SilentTremor's solution into React/JS-Class:
class SVGToPNG {
static convert = function (src) {
var img = new Image();
img.onload = function () {
var canvas = SVGToPNG.#convertImageToCanvas(img);
var pngImage = SVGToPNG.#convertCanvasToImage(canvas);
var anchor = document.createElement("a");
anchor.setAttribute("href", pngImage.src);
anchor.setAttribute("download", "image.png");
anchor.click();
};
img.src = src;
};
static #convertImageToCanvas = function (image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
};
static #convertCanvasToImage = function (canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
};
}
export default SVGToPNG;
Usage:
let dataUrl = someCanvas.toDataURL("image/svg+xml");
SVGToPNG.convert(dataUrl);

Duplicating a canvas many times: clone the canvas or copy the image data?

One of my interface elements is being rendered using the HTML5 <canvas> element and associated JavaScript API. This element is used in several places on the same screen and on multiple screens throughout the app. What is the most efficient way to display this everywhere it's required?
My first idea is to draw to a master canvas, which I then clone and insert where needed in the page. The master canvas might be something like:
var master = $('<canvas>').attr({
width: 100,
height: 100
}),
c = master[0],
ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
Let's say I want to duplicate the canvas in these div containers:
<div class="square-container" id="square_header"></div>
...
<div class="square-container" id="square_dataTable"></div>
...
<div class="square-container" id="square_gallery"></div>
....
When the page loads, I'll do this to insert a duplicate canvas element into each container:
$(document).ready(function() {
$('.square-container').each(function() {
master.clone().appendTo($(this));
});
});
The content being rendered on the canvas is going to be more complex than the simple square used in this example but will still end up being just a static image. It is possible, though, that there could be dozens of different images each cloned dozens of times per page.
The other approach I had in mind was to create an image using the toDataURL() method and set that as the appropriate images' sources:
var master = $('<canvas>').attr({
width: 100,
height: 100
}),
c = master[0],
ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
var square = c.toDataURL('image/png');
I would add image tags where necessary:
<img src="" id="square_header" class="square" alt="" />
...
<img src="" id="square_dataTable1" class="square" alt="" />
...
<img src="" id="square_gallery" class="square" alt="" />
....
And then set all of their SRCs to that newly created image:
$(document).ready(function() {
$('img.square').attr('src', square);
});
To me, it pretty much looks like six of one, half dozen of the other. But I'm wondering if one way is considered better practice than the other? If the content being rendered on the <canvas> were more complex, would one way be more efficient than the other?
In that same spirit, when I need to use that element on subsequent pages, is it best to execute all the javascript (from whatever solution is deemed best above) on each page or would saving the value of CANVAS_ELEMENT.toDataURL() in a cookie and then using that on subsequent pages be any more efficient?
Cloning a canvas will duplicate its dimensions and styling, but not its image data. You can copy the image data by calling drawImage on the context. To paint the contents of originalCanvas onto duplicateCanvas, write:
duplicateCanvas.getContext('2d').drawImage(originalCanvas, 0, 0);
As a demonstration, the following snippet generates four canvases:
an original canvas with a small scene painted onto it
a copy made by calling cloneNode only
a copy made by calling cloneNode and drawImage
a copy made by creating a new image and setting its source to the data URI
function message(s) {
document.getElementById('message').innerHTML += s + '<br />';
}
function timeIt(action, description, initializer) {
var totalTime = 0,
initializer = initializer || function () {};
initializer();
var startTime = performance.now();
action();
var elapsed = performance.now() - startTime;
message('<span class="time"><span class="number">' +
Math.round(elapsed * 1000) + ' μs</span></span> ' + description);
}
function makeCanvas() {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d');
canvas.width = 100;
canvas.height = 100;
timeIt(function () {
context.fillStyle = '#a63d3d';
context.fillRect(10, 10, 80, 40); // Paint a small scene.
context.fillStyle = '#3b618c';
context.beginPath();
context.arc(60, 60, 25, 0, 2*Math.PI);
context.closePath();
context.fill();
}, '(millionths of a second) to draw original scene', function () {
context.clearRect(0, 0, canvas.width, canvas.height);
});
return canvas;
}
// copyCanvas returns a canvas containing the same image as the given canvas.
function copyCanvas(original) {
var copy;
timeIt(function () {
copy = original.cloneNode(); // Copy the canvas dimensions.
copy.getContext('2d').drawImage(original, 0, 0); // Copy the image.
}, 'to copy canvas with cloneNode and drawImage');
return copy;
}
// imageFromStorage extracts the image data from a canvas, stores the image data
// in a browser session, then retrieves the image data from the session and
// makes a new image element out of it. We measure the total time to retrieve
// the data and make the image.
function imageFromStorage(original) {
var image,
dataURI = original.toDataURL();
timeIt(function () {
image = document.createElement('img');
image.src = dataURI;
}, 'to make image from a dataURI');
return image;
}
function pageLoad() {
var target = document.getElementById('canvases'),
containers = {}, // We'll put the canvases inside divs.
names = ['original', 'cloneNode', 'drawImage', 'dataURI'];
for (var i = 0; i < names.length; ++i) {
var name = names[i], // Use the name as an ID and a visible header.
container = document.createElement('div'),
header = document.createElement('div');
container.className = 'container';
header.className = 'header';
header.innerHTML = container.id = name;
container.appendChild(header);
target.appendChild(container);
containers[name] = container; // The canvas container is ready.
}
var canvas = makeCanvas();
containers.original.appendChild(canvas); // Original canvas.
containers.cloneNode.appendChild(canvas.cloneNode()); // cloneNode
containers.drawImage.appendChild(copyCanvas(canvas)); // cloneNode + drawImage
containers.dataURI.appendChild(imageFromStorage(canvas)); // localStorage
}
pageLoad();
body {
font-family: sans-serif;
}
.header {
font-size: 18px;
}
.container {
margin: 10px;
display: inline-block;
}
canvas, img {
border: 1px solid #eee;
}
#message {
color: #666;
font-size: 16px;
line-height: 28px;
}
#message .time {
display: inline-block;
text-align: right;
width: 100px;
}
#message .number {
font-weight: bold;
padding: 1px 3px;
color: #222;
background: #efedd4;
}
<div id="canvases"></div>
<div id="message"></div>
If you call toDataURL to copy the image data into a string for use in other pages, don't put the string into a cookie. Cookies are meant to store small amounts of data. Instead, use the HTML5 Web Storage API to store the image data in the browser. Alternatively, if the image doesn't change between user sessions, you can render it to a PNG image on a server and use the Cache-Control header to encourage the browser to cache the image file for fast retrieval.
When it comes to the performance of client-side image rendering, it may be faster to draw the scene anew than to paint the stringified image data onto the canvas. Decoding the string and painting the pixels is a relatively expensive operation. To find out if it makes sense to redraw the scene on each page, you can time your drawing operations with performance.now, as demonstrated in the snippet.

Pre-load image before using it

I'm using an image that needs to change when you click on it and to do that I'm using a JavaScript onclick. There a brief "flick" the first time I do it while it load the image but this only happens the first time. Is there a way to preload the second image so the change it as smooth the first time as it is all the others?
Preloading images is a great way to improve the user experience. You have 3 Ways to Preload Images with CSS, JavaScript, or Ajax:
Method 1: Preloading with CSS and JavaScript
#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }
#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }
#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }
By strategically applying preload IDs to existing (X)HTML elements, we can use CSS’ background property to preload select images off-screen in the background. Then, as long as the paths to these images remains the same when they are referred to elsewhere in the web page, the browser will use the preloaded/cached images when rendering the page. Simple, effective, and no JavaScript required.
Method 2: Javascript Only
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"http://domain.tld/gallery/image-001.jpg",
"http://domain.tld/gallery/image-002.jpg",
"http://domain.tld/gallery/image-003.jpg"
)
Source: Perishable Press
Something like :
image = new Image();
image.src = "image.jpg";
image.onLoad = function(){
alert("image ready");
}
Or with more images :
function all_images_preloaded(){
alert("all images are ready to use");
}
var imgs = [
"image1.jpg"
, "image2.jpg"
, "image3.jpg"
];
var count = imgs.length;
var count_loaded = 0;
for(i in imgs){
image = new Image();
image.src = "image.jpg";
image.onLoad = function(){
count_loaded++;
if(count_loaded == count){
all_images_preloaded();
}
}
}

Categories

Resources