Best way to get new Image in Javascript using canvas - javascript

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";

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">

Determine when canvas content is loaded

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

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);
}
}
});

Trying to draw an image to canvas and then use Caman.js to manipulate this image

So far I have this piece of code;
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
to draw an image to the canvas and then I have this code
%img#example{"data-caman-hidpi" => "images/example1_1200.jpg", src: "images/example1_600.jpg"}/
which manipulates a image stored in images/ but being new to canvas and not having much javascript knowledge, I'm not sure how to go about amalgamating these two pieces of code so that they work together. I want to be able to choose an image from my computer and for this to be drawn onto the canvas and then for to be able to use Caman.js to manipulate this image. Any help would be much appreciated.
I have the same issue. The fix for me was to add this attribute to the canvas element 'data-caman-hidpi-disabled'.
The bug only effects retina screens. More information here: https://github.com/meltingice/CamanJS/issues/188
I think it would be easier to load the image to an <img> element then call CamanJS's constructor on it. This will replace the <img> element with a <canvas> element
HTML
<img src="something" id="imagesrc">
Javascript
Caman('#imagesrc', function(){
//manipulate image
});
If you'd like to use a Canvas object directly like what you did, you use the same Javascript code but using your canvas object. Caman will manipulate the same canvas object.
Caman('#imageCanvas',function(){
//manipulate image
});
More info here: http://camanjs.com/guides/#BasicUsage

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