Determine when canvas content is loaded - javascript

Is there a way to detect when canvas content is loaded? What I'm trying is following. I need to print a page where in a widget is rendered a pdf document using the pdfjs library. Only the first pdf page have to be printed alongside with the content of the web page where the widget is placed. My approach was to get the canvas of the first pdf page which the pdfjs library created and put its content as source of an img element.
var content = canvas.toDataURL();
var img = document.createElement('img');
img.setAttribute('src', content);
widget.parentNode.insertBefore(img, widget);
Now if I use this as is, the image is created but is blank. If I put the code above inside setTimeout with a few seconds delay the image is rendered properly with the content of the first pdf page but this is not reliable for me. I've checked the content returned by canvas.toDataURL() in both cases and it appeared not equal so this was the reason for my conclusion that the content of the canvas was not loaded yet.
Any ideas for solution would be appreciated.

canvas will bind to the DOM like any other html tag. But your problem is image is not loading at very first time. So use onload method for loading images.
Refer HTML5 Canvas Load Image Data URL
EDIT :
drawImage() method draws an image or video onto the canvas. So use that method to draw the image on canvas.
Here is the updated code:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 10, 10); // here this = image, 10 = width of the image, 10 = height of the image
};
imageObj.src = dataURL;
For more information see here

Related

Using JavaScript, can I save images as their CSS thumbnailed sizes?

Perhaps an odd use case, but assume the following code, where image1.jpg is 1920x1080:
<a href="http://example.com/dir/photos/image1.jpg" target="_blank">
<img src="http://example.com/dir/photos/image1.jpg">
</a>
As you can see, the image loads in full on the page; however, not shown above is CSS that's being used to display that image as a thumbnail on the page (say, 480 x 270).
Yes, this is a horribly unoptimized practice.
The issue I'm having is that a client has hundreds of these occurrences happening across multiple pages. I'm trying to quickly create thumbnail versions of the images exactly as they're sized on the page. Some images are wider/taller than others, and image/folder names are all over the place, so creating thumbnails of each image from the rendered page is what I need for what I would like to accomplish.
Ideally, I'm thinking of using JS (or jQuery, if anyone knows of any particular methods) to target all the images (however that needs to happen) to ultimately create and download/save thumbnails as their CSS-sized on-page representations.
I hope this question makes sense. I would be happy to clarify more if need be. Thank you for any assistance you can provide!
The following code, takes all images from a page, and scales them to the effective CSS size being used for rendering, then performs the download.
The way it works is the following:
Generates an empty canvas element
Generates an image, and loads the original image element source in it
Dumps the content of the new image in the canvas, using the original image sizes.
Dumps the content of the canvas back into the original image element
Executes the download() function (only works in chrome)
function scaleToElementSize(img){
return new Promise( (resolve,reject)=>{
// create an empty canvas and assign to it
// the rendered proportions of the provided image
let c = document.createElement('canvas');
c.height = img.height;
c.width = img.width ;
const ctx = c.getContext("2d");
// create an image element, and load the source
// image in it
let i = new Image();
i.setAttribute('crossOrigin', 'anonymous');
i.src = img.src;
// when image is loaded, copy its contenta scaled
// into the canvas, dump the resulting scaled
// image back, to the original image, and download
i.onload = ()=>{
ctx.drawImage(i, 0, 0, c.width, c.height);
img.setAttribute('filename', img.src);
img.onload = null;
img.src = c.toDataURL("image/png");
resolve();
}
});
}
function download(img){
var link = document.createElement('a');
link.download = img.getAttribute('filename');
link.href = img.src.replace("image/png", "image/octet-stream");;
link.click();
}
document.querySelectorAll('img').forEach( img=>{
img.onload= function(){
scaleToElementSize(img)
.then( ()=> download(img) )
}
})
<img src="https://placekitten.com/200/286?a.jpg" width="100">
<img src="https://placekitten.com/200/139?b.jpg" width="200">
<img src="https://placekitten.com/408/287?c.jpg" width="110">

Best way to get new Image in Javascript using canvas

I am making a game with the html5 canvas and I am having some trouble getting the images on screen.
//player img
var img1 = new Image();
img1.onload = function() {
console.log("image loaded");
};
img1.src = "player.png";
The image is a .png file called "player" and is saved on my desktop. Am I doing something wrong when setting the src method? Is there a better way to do this? I appreciate any help.
Well first, the image should have a path that is relative to the html document and if you are not seeing the image, it's probably because you didn't put that relative path into your code (you are only using the file name which implies the image is in the same directory as the html file).
Also, you haven't shown any code to associate the image with the canvas. This is the approach:
// Get the DOM object reference for the canvas element:
var canvas = document.getElementById("canvas");
// Get an object reference for the canvas' contextual environment:
var ctx = canvas.getContext('2d');
// Instantiate an image to use as the background of the canvas:
var img = new Image();
// Make sure the image is loaded first otherwise nothing will draw.
img.addEventListener("load", function () {
// Draw the image on the canvas at position 0, 0 (top-left):
ctx.drawImage(img, 0, 0);
});
// Wait until after wiring up the load event handler to set the image source
// This example assumes that the image is located in a sub-folder of the current folder, called images.
// Your path must be a relative reference to the location where the image is.
img.src = "images/starfield.jpg";

How to resize canvas contents and upload image to server?

I have been trying to figure out how I could resize the canvas contents to get roughly a 100x100 thumbnail and upload it to the server. I would like to keep my existing canvas in its current size, because all these actions have to be invisible to the user.
I know I can get the contents in the current size of the canvas by using toDataURL, but how could I resize it and then upload to the server?
var image = canvas.toDataURL("image/png");
You can create canvas in your JS script (without appending it to DOM), then draw on it your content from working canvas (your image), resize it in context of your temp canvas ( Post about resizing in canvas ). And only then do canvas.toDataURL("image/png"); to get resized image. Then you send it as base64 string and save on your server as png file.
Thanks to Alexander Kremenets I managed to put together the code I needed. I used the Hermite resize from the question Alexander linked. Also combined code from other questions coming up with this:
var originalCanvas = document.getElementById("c");
// Create canvas for resizing
var resizeCanvas = document.createElement("canvas");
resizeCanvas.height = originalCanvas.height;
resizeCanvas.width = originalCanvas.width;
var resizeCtx = resizeCanvas.getContext('2d');
// Put original canvas contents to the resizing canvas
resizeCtx.drawImage(originalCanvas, 0, 0);
// Resize using Hermite resampling
resampleHermite(resizeCanvas, resizeCanvas.width, resizeCanvas.height, 150, 90);
// Use the resized image to do what you want
var image = resizeCanvas.toDataURL("image/png");

simple HTML5 canvas image not displaying

I'm new to this - I just can't figure out why this isn't working. When I remove Display:none from HTML, the image works correctly so I know the path to the image is correct. But it's not drawing on the canvas. Thanks for your time.
HTML:
<canvas width="840" height="900" id="Canvas6">
Your browser does not support this feature.
</canvas>
<img src="image/logo.png" id="img1" width="825" height="272" style="display:none;">
<script type="text/javascript" src="js/main.js"></script>
Main.JS JAVASCRIPT:
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
//Create a variable to hold our image
var srcImg = document.getElementById("img1");
//Draw an image directly onto the canvas
ctx.drawImage(srcImg, 0,0);
//Draw a scaled down image
//drawImage(srcImg, dx, dy, dw, dh)
}
}
In html file, the first best thing you have done is used the 'script' tag right at the end of the html file.
This ensures that the "Critical Render Time" is minimized, and the display items in HTML are shown first. (Not a huge impact on this case, because here you are using the JS to draw/display, but this approach is really good when you use your js for other purposes like calculations etc., and you don't want to stop the other HTML items from displaying because of an ongoing calculation.)
Now that the canvas is ready, its time to throw the image on the canvas.
Try using the border property (style="border: 2px dotted black") to see the container area of the canvas.
Hmmm !! But the image doesn't show in canvas. WHY ??
Images(or any other files) take atleast some time to get processed. By the time they are getting processed to be loaded on the screen, your canvas is already getting displayed. Hence you see an empty canvas.
So, the solution is to make everything else wait, till the time image gets loaded.
How do we do that ? Just use the "Event Listener".
EventListener is the property of Window object. (window.addEventListener("load", some_func_to_run , false);). We generally use this, when we want our window/page/browser to wait for something, but hey , we can use it for our images as well.
var cvs = document.getElementById("canvas"); // Getting the control of the canvas
var ctx = cvs.getContext("2d"); //Getting the control of the useful HTML object getContext . This object brings in a lot of useful methods like drawImage, fillRect etc.
//create images
var bg = new Image(); // Creating image objects
bg.src = "images/bg.png"; //Setting the source file
//create images ends
//load images first
bg.addEventListener("load" , draw , false); //**IMPORTANT : Just remove this line and you will start facing this problem of empty canvas again
//loading images ends
function draw() {
ctx.drawImage(bg,0,0); // Putting the image and its coordinates on the canvas
}
draw(); // Calling the draw function to put the image on canvas
<html>
<body>
<canvas id="canvas" width="288" height="512" style="border: 2px dotted black"> </canvas>
<script src="flappyBird.js"></script>
</body>
</html>
So, it all about using Event Listener and asking everything to wait till the image gets loaded.
Hope this help. :)
If you try to place an image on a Canvas before it has loaded, it will not show. It is not like the img tag that will show the image whenever it loads. I surrounded your JS with an onload and it worked for me.
document.getElementById("img1").onload = function() { /* Your JS */ };
You have to wait for the image to load before you can draw it on the canvas, so set your drawing code to run on the window load event (by which time all images are loaded). Also, you don't need to include the markup for the image on the page, where you have to then prevent it from displaying with CSS. You can just create the image object and set the source attribute in the javascript. For example:
var img = document.createElement('img');
img.src = 'image/logo.png';
window.addEventListener('load', function(){
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
ctx.drawImage(img, 0,0);
}
}
});

Resize image for download client side

Is there any way through any type of client side script to get an external image (ex: http://www.google.com/image.jpg) and resize it when the user copies the image so that the pasted image will be resized? And I can't get HTML5 canvas to work.
I'm working out of Dreamweaver CS5.5 and creating an Air App. The code works in live view but not when I preview the Air App. Here is the code that is not working:
function test(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
context.drawImage(img, 0,0);
};
img.src="image.jpg";
}
You can try drawing the image then doing img.src = canvas.toDataURL('image/png') prior to the user dragging. This will cause the canvas to output its data to the image tag. The canvas should be invisible, while the image is the visible element the user should drag.
To resize the image, specify the width and height in the drawImage.

Categories

Resources