How to get the image preload in javascript - javascript

I have a preload link in my html.
<link rel="preload" href="sprite.png" id="mySprite" as="image">
How can I convert this to a Image in Javascript?
(let sprite = new Image(myPreloadeImageFromHTML)
I have a lot of images needed, but they do not load on time, which results in no images shown.
How can I preload it and obtain it in Javscript as an Image using a <link rel="preload">?

I have created a link and a canvas in HTML and using javascript I am fetching that link href then created an image from that link and then inserted that image into the canvas.
HTML:
<!-- Your Link -->
<link rel="preload" href="https://www.android-examples.com/wp-content/uploads/2016/03/demo_image.jpg" id="mySprite" as="image">
<!-- Create Canvas -->
<canvas id="my-canvas" />
JS:
var img1 = new Image();
img1.src = document.getElementById("mySprite").href;
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
img1.onload = function () {
c.width = img1.width;
c.height = img1.height;
ctx.drawImage(img1, 0, 0);
}
Here is the reference:
https://jsfiddle.net/uLwpsdqt/

Related

Add images to html canvas

Im trying to set up a background image in my html canvas by creating a function that clears the canvas and draws the background image to fill the canvas. I've been trying to figure out where I went wrong and why no images are appearing on preview. (I've already double checked my links for spelling errors)
`<html>
<head>
<title>Apple Dropper</title>
<meta charset = "utf-8">
<script src ="proa1.js">
// set src of images in variables
var canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 400;
let bg = new Image();
bg.src = "projectimages/gifani.gif";
let pic = new Image(0,350);
pic.src = "projectimages/bucket.png";
let fish = new Image(300,0);
pic.src = "projectimages/fish.png";
// Make sure the image is loaded first otherwise nothing will draw.
bg.onload = function(){
ctx.drawImage(bg,0,0);
}
</script>
</head>
<body>
<h1>CPSC 1045 Apple Dropper Project</h1><br>
<h2>Alleluia Anteros</h2>
<!--- canvas --->
<canvas id="myCanvas" width="600" height="400" style="border:1px solid #000000;" >
</canvas>
<br>
<!--- control panel --->
</body>
</html>`
If you want a regular background image it would be much easier to do so using CSS. You would select the body tag and use the background-img property with the value of URL and put the URL of the image in the parenthesis. To make to cover the page you would have to use the property of background-size with the value of cover.
body{
background-img:url(bckgrndimg.png);
background-size:cover;
}

pdfmake - Transform SVG to image64 in ANGULAR 4

I'm trying to transform an SVG into an image with pdfmake.
const svg = document.getElementById('chart-grafico-pizza').childNodes[0];
const img = document.createElement('img');
const canvas = document.getElementById('teste-canvas');
// get svg data
const xml = new XMLSerializer().serializeToString(svg);
// make it base64
const svg64 = btoa(xml);
const b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
const image64 = b64Start + svg64;
// set it as the source of the img element
img.src = image64;
// draw the image onto the canvas
(canvas as HTMLCanvasElement).getContext('2d').drawImage(img, 0, 0);
The image is always returned as undefined.
I don't see any problems with your code, neither with SVG.
Your code, which you obviously got from here
Drawing an SVG file on a HTML5 canvas
works perfectly fine, assuming that your query selectors work. Which probably is exactly the issue here... Since you did not provide your HTML, we can of course not check for that.
https://jsbin.com/qacodugive/1/edit
What do you mean by "the image is undefined"? The variable img clearly isn't. It's a DOM Element at any point in time.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div>SVG here</div>
<svg height="100">
<rect width="100" height="100" />
</svg>
<div>Canvas here (Click "Run with JS" to render)</div>
<canvas></canvas>
</body>
</html>
JS
var svg = document.querySelector('svg');
var img = document.createElement('img');
var canvas = document.querySelector('canvas');
// get svg data
var xml = new XMLSerializer().serializeToString(svg);
// make it base64
var svg64 = btoa(xml);
var b64Start = 'data:image/svg+xml;base64,';
// prepend a "header"
var image64 = b64Start + svg64;
// set it as the source of the img element
img.src = image64;
// draw the image onto the canvas
canvas.getContext('2d').drawImage(img, 0, 0);

Javascript : Upload Image file and resize to different resolution then download

Please suggest some library for Image processing.
We tried to draw image to canvas and then to download the image of required size, but not achievable.
We like to use this mechanism to reduce image processing in back-end server
Below is the code we tried
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Image Resize</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form>
<input id="filez" type="file" value="img">
<div id="parentDiv"></div>
</form>
</body>
<script type="text/javascript">
$(document).ready(function(){
function ImageResizeObject(parentElement,fileElement,objz){
this.parentElement = $(parentElement);
this.fileElement = document.getElementById(fileElement);
this.objz = objz;
this.imageFile = this.fileElement.files[0];
this.parentElement.empty();
for(var i=0;i<this.objz.length;i++){
var parentDiv = $("<div></div>");
parentDiv.attr("id","parentDiv parentDiv"+i);
var canvas = $("<canvas id='parentDivCanvas"+i+"'></canvas>");
canvas.css({"height":objz[i].height,"width":this.objz[i].width});
parentDiv.append(canvas);
this.parentElement.append(parentDiv);
var ctx = canvas[0].getContext('2d');
var img = new Image();
img.src =URL.createObjectURL(this.imageFile);
ctx.drawImage(img,0,0,img.width,img.height,0, 0,canvas.width(),canvas.height());
}
}
$("#filez").on('change', function(){
console.log("file uploaded");
FileUpload = new ImageResizeObject("#parentDiv","filez",[{"height":"410","width":"410"},{"height":"205","width":"205"}]);
});
});
</script>
</html>
On Stackoverflow, we don't make library recommendations, but...
You can use html5 canvas to resize images.
Create a canvas element
Size it to your desired scaled size
Draw the image onto the canvas with scaling to the desired size
Create a resized imageObject using the canvas as the image.src
Here's example code and a Demo:
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/marioRunningRight1.png";
function start(){
resizeImg(img,0.50);
resizeImg(img,2);
}
function resizeImg(img,scaleFactor){
var c=document.createElement('canvas');
var ctx=c.getContext('2d');
var iw=img.width;
var ih=img.height;
c.width=iw*scaleFactor;
c.height=ih*scaleFactor;
ctx.drawImage(img,0,0,iw*scaleFactor,ih*scaleFactor);
var scaledImg=new Image();
scaledImg.onload=function(){
// scaledImg is a scaled imageObject for upload/download
// For testing, just append it to the DOM
document.body.appendChild(scaledImg);
}
scaledImg.src=c.toDataURL();
}
<h4>Original image</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/marioRunningRight1.png' crossOrigin='anonymous'>
<br>
<h4>Resized images at 50% and at 200%</h4>

Writing text on an image in javascript

I need to add text to an already uploaded image and then upload the new image with the text back onto the server.
I'd like to use an image which is already on the server, which means that I have a variable $image_location linking directly to the image already set.
I found some code on StackOverflow which enables putting text on the image which you upload through the upload form.
My question is how would I change it so that instead of uploading the image, I could use the image already on my server.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
var
maxSize=600, // Max width or height of the image
font='italic small-caps bold 40px/50px arial', // font style
fontColor='white', // font color
textX=50, // text x position
textY=50, // text y position
h=function(e){
var fr=new FileReader();
fr.onload=function(e){
var img=new Image();
img.onload=function(){
var r=maxSize/Math.max(this.width,this.height),
w=Math.round(this.width*r),
h=Math.round(this.height*r),
c=document.createElement("canvas"),cc=c.getContext("2d");
c.width=w;c.height=h;
cc.drawImage(this,0,0,w,h);
cc.font=font;
cc.fillStyle=fontColor;
cc.fillText(document.getElementById('t').value,textX,textY);
this.src=c.toDataURL();
document.body.appendChild(this);
}
img.src=e.target.result;
}
fr.readAsDataURL(e.target.files[0]);
}
window.onload=function(){
document.getElementById('f').addEventListener('change',h,false);
}
</script>
</head>
<body>
1.write text
<input type="text" id="t">
2.add image
<input type="file" id="f">
</body>
</html>
You can load an image to the canvas like so:
var img = new Image();
img.onload = function(){
c.width = img.width;
c.height = img.height;
cc.drawImage(img, 0, 0, img.width, img.height);
}
img.src = '/path/to/image.jpg';
so it looks like the only thing you'd need to change is the img.src variable

Function that returns the data URI Base64 string of image in Javascript

I'm really struggling to write a function for getting the Base64 encoding of an image. Since this function will be part of a bigger script that uses jsPDF.js to make PDFs on-the-fly from a website, It's important the be able to calculate those Base64 encodings as the result of a function. The images will be hosted on the same server, so no same-origin issues. I know the .toDataURL() method of the canvas element can do this and I also know that the image needs to be fully loaded in order to get the Data URL correctly, so I wrote this function
// Encode image to Base64
function encodeBase64(url, format)
{
var image = new Image(),
canvas = document.createElement("canvas"),
context = canvas.getContext("2d");
image.src = url;
image.onload = function ()
{
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
var dataURL = canvas.toDataURL(format);
alert(dataURL);
};
}
The problem is that I don't know how to "extract" the dataURL value from the onload function so that the encodeBase64 function simply returns that value and I can put it in an array. Alert returns that string correctly so I'm sure the code works, but if I try to write any other statement like "return dataURL" or similar I just get undefined value. Please help.
First load all the images into an array.
Then create the dataURLs using canvas and load the dataURLs into a second array.
Example code and a Demo: http://jsfiddle.net/m1erickson/fbdb3qbw/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// array for dataURLs
var dataURLs=[];
// put the paths to your images in imageURLs[]
var imageURLs=[];
// push all your image urls!
imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/sun.png",format:null});
imageURLs.push({url:"https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp1.png",format:'image/jpeg'});
// the loaded images will be placed in images[]
var imgs=[];
var imagesOK=0;
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
img.format=imageURLs[i].format;
imgs.push(img);
dataURLs.push('');
img.index=imgs.length-1;
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i].url;
}
}
function start(){
// the imgs[] array now holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// now loop through each img and create its dataURL
for(var i=0;i<imgs.length;i++){
var img=imgs[i];
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
dataURLs[img.index] = canvas.toDataURL(img.format);
}
// Demo: report the results to the console
console.log(dataURLs);
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Fetch dataURLs from images (see results in the console)</h4>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
[ Addition: pulling urls from textarea ]
Here's how to pull the urls from the textarea.
(#loadImages is a button that's pushed when your user has typed the urls into the textbox).
I haven't looked at the jsPDF source so I can't speak to your dims issue.
$('#loadImages').click(function(){
var inputText = document.getElementsByTagName("textarea")[0].value.split("\n");
for(var i = 0; i < inputText.length; i++){
imageURLs.push({url: inputText[i],format:"image/jpeg"});
}
loadAllImages(start);
});

Categories

Resources