Canvas drawImage() not working - javascript

This Javascript code draw part of the image on the canvas:
var img = document.getElementById('img');
var canvas = document.getElementById('can');
//canvas.width = img.width;
//canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
But when I uncomment the middle lines to set the canvas width and height, the drawImage() does not work.
What should I check in order to find the problem?

You need to wait for the browser to load the image.
Use onload event if image was not yet loaded and change your code to something like this:
var img = document.getElementById('img');
var canvas = document.getElementById('can');
var ctx = canvas.getContext("2d");
var callback = function(image) {
if(!image) image = this;
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(image, 0, 0);
}
if(img.complete) { //check if image was already loaded by the browser
callback(img);
}else {
img.onload = callback;
}
See this working demo

var img = document.getElementById('img');
Try naming the variable something else. Also make sure some image is loaded.
Try my fiddle http://jsfiddle.net/aliasm2k/tAum2/ for more ideas

The width and height image attributes aren't set until the image is loaded, so i propose you to put your code in onLoad() image event.

Related

Can't get base64 resized image from javascript canvas

I have two main questions. I'm trying to resize a base64 image according to the answer in
JavaScript reduce the size and quality of image with based64 encoded code
This seemed simple enough, except for the fact that I need to get only the base64 string from that function, without the data:image... header.
I tried to modify the function like this:
function resizeBase64Img(base64, width, height) {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
var deferred = $.Deferred();
$("<img/>").attr("src", "data:image/gif;base64," + base64).load(function () {
context.scale(width / this.width, height / this.height);
context.drawImage(this, 0, 0);
deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));
});
var result = canvas.toDataURL();
return result.substr(result.indexOf(",") + 1)
}
which returns a base64 string. This string is corrupted, and it never displays correctly. Why is this happening and how can I fix it?
The other question is, is there a way to resize the image based on percentage and not on pixel size?
Thanks
I ended up rewriting the function based on another canvas function I found. This function takes the src of a base64 img, modifies the size and assigns the result in base64 to another element:
function resizeBase64Img(url, width, height) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.scale(width/this.width, height/this.height);
ctx.drawImage(this, 0, 0);
result=canvas.toDataURL();
$('#ASSIGNEDELEMENT').val(result.substr(result.indexOf(",") + 1));
};
img.src = url;
}
And it should be invoked like this:
resizeBase64Img($('#image').attr('src'),300,300);

canvas context getImageData() function won't execute, probably because it's executed before the image is loaded

what I'm trying to do is draw an image to an html canvas using only javascript, and by using the getImageData() function, I'm trying to get the image's bits and then manipulate them in multiple ways.
however, because i'm loading the image using javascript, my suspicion is that the image can't load in time before the call to getImageData(), so the program just stops working when that call is made, as you can see the _log(3) statement isn't being called.
this happens even though I've called getImageData() function inside the images onload() event.
i've already seen a few suggestions in some other stackoverflow threads regarding this issue, but none of them seem to work for me.
any help in the right direction would be really appreciated.
here's the jsfiddle: https://jsfiddle.net/houqdfx9/2/
this is the html:
<p id="log"></p>
this is the javascript:
function _log(string){
document.getElementById("log").innerHTML += string;
}
function _createCanvas(){
var canvas = document.createElement("canvas");
canvas.setAttribute("id", "canvas");
document.body.appendChild(canvas);
return canvas;
}
function _drawAndProcessImage(img, ctx){
ctx.drawImage(img, 0, 0);
_log(img.width + " " + img.height + " ");
var img_data = ctx.getImageData(0,0,img.width,img.height);
_log(3);
/* DO THINGS WITH THE IMG_DATA HERE */
}
function setCanvasAndLoadImage(url, canvas, callback) {
var img = new Image;
var ctx = canvas.getContext("2d");
img.onload = function(){callback(img, ctx);};
img.src = url;
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
};
var canvas = _createCanvas();
setCanvasAndLoadImage("https://pixabay.com/static/uploads/photo/2014/02/01/17/30/apple-256267_960_720.jpg", canvas, _drawAndProcessImage);
Please try this. This works. But, there is a cross domain violation because of the different domains. You would need to proxy this through a server maybe. See this for a solution.
function _log(string){
document.getElementById("log").innerHTML += string;
}
function _createCanvas(){
var canvas = document.createElement("canvas");
canvas.setAttribute("id", "canvas");
document.body.appendChild(canvas);
return canvas;
}
function _drawAndProcessImage(img, ctx){
ctx.drawImage(img, 0, 0);
_log(img.width + " " + img.height + " ");
var img_data = ctx.getImageData(0,0,img.width,img.height);
_log(3);
/* DO THINGS WITH THE IMG_DATA HERE */
}
function setCanvasAndLoadImage(url, canvas, callback) {
var img = new Image;
var ctx = canvas.getContext("2d");
img.onload = function() {
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
callback(img, ctx);
};
img.src = url;
};
var canvas = _createCanvas();
setCanvasAndLoadImage("https://pixabay.com/static/uploads/photo/2014/02/01/17/30/apple-256267_960_720.jpg", canvas, _drawAndProcessImage);
<p id="log"></p>
I think the problem is stems from the lines
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
You are asking for the image dimensions but the image has not been loaded. You have to move that to the image's onload event.

Image not getting copied properly in javascript

I need images to be copied and sent to server for image rotations etc.
To copy an image I'm using this code( from Get image data in JavaScript?):
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
var replaced = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log("dataurl=",dataURL);
console.log("replaced=",replaced);
return replaced;
}
It is called like this:
$("#xyz").load(send_image).each(function () {
if (this.complete)
$(this).load();
});
function send_image(){
getBase64Image(document.getElementById('xyz'));
}
However in getBase64Image function once in 40-50 times dataURL is being returned as empty.
What could be the reason?

fill the image within the canvas

I have a base64 image string, I have created a canvas and put the base64 with the image and have given canvas height as 481 and width as 650, when I tried to display the image in html, image is coming but it is not completely filling the canvas,
Can anyone please tell me some solution to fill the image within the entire canvas, no matter what the quality of the picture.
My code is as given below
JSFiddle
var base64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBA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GSDmnzkewVr9Siyrj7pJ+tdCbPInBdtSIqB2xV3OdwS8iNx6VSZhUi+hPYWZlkVmTODnBFZ1qnKrJnZl2CdaalJXOqtUu4rUrFEyQ4G5sdRXkVHCU7t6n3dBOEFTSskM+zyNJtVQT1O3kYqudJXZTpXl69iGSPLEkcVaehhUpe9foVpRg4A61rHVHDWTi9Ci0LddtbqR486L7Dfs7HPH6U+ch4eT6Fq00g3BTKMzNwqgck1lUxHId2HylVEp1PuO5svBRt4lBjd3+UudvC57D1r5+rmnPLRntUvZ4aPLFGtqWllrb7NZxDCJt2n0rjo17T5pscZ8suZswWsvIl2II0Ro+S/Qe/vXoqrzq77mvNeKiuhkXUUcaqAQdv3iDwTXbTk5MuStC8mZ0+M5HeumB5uIte6JPJG7AXn0NTzaG/sFzWSNbSPD5vv9JnDRwDODt+8RXHicX7L3Y6s1hRgnzM7DwDoKXF9JfTRBEjOIyemO+PfpXl5jXXsvZJ6seOqyilFdTttRQ2yuscuGfsOmK+fpO7V1scS5YanP6heQxx7liUS9OOp+vtXfCM6sveehsoN6s47WI2dVeMEtyzrjoPT8K9nDO10zpopbs5123HcCw3EDpxXpJW0NXbdPcq3C4OR9DW8GcGJgk7o0fC8Eer6ta2l4CY5HG4LxmscV+5g5QHhq068bz7XPQPERW1tWjgiREj+RVA4AFfN0L1K15HRS95Rm93udD4XtrdI7GNYlCysC2O/BrkzGTuc9fWbNC+bBuJcAsrlBkdBXJhlzR17HLD3lqctp1vFI93dSAtIucZPSu+rJpRgtjsnojImRJb8l1B3Jgjtg13J8sLIq7aOXv0W1llihGF80Jg+ma9Sk3UScuxvGbsmZV0uHdcnANdsNkY4lWbR//9k=";
var canvas = document.createElement('canvas');
canvas.width = 650;
canvas.height = 481;
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function () {
ctx.drawImage(image, 0, 0);
};
image.src = base64;
$('#showImage').html(canvas);
Change your onload function body to
ctx.drawImage(image, 0, 0, 650, 481);
Set the size of the canvas using natural width/height after the image has loaded:
var base64 = "data:image/jpeg;base64,/9j/4AAQSkZJ.....";
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function () {
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0, 0);
};
image.src = base64;
$('#showImage').html(canvas);

How to draw existing <img> to canvas

I know I can do this using javascript:
var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context
var img = new Image();
img.src = 'test.png';
img.onload = function(){
ctx.drawImage(img, 200, 200); // x, y, width, height
}
But how to draw existing tag to canvas:
In html:
<img src='test.png'>
Why I want to do this? I want to optimize image loading using pagespeed
The very first google hit for your question is promising:
var c=document.getElementById("testCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("existingHTMLImageElementId");
ctx.drawImage(img,10,10);
See w3Schools
Try
var canvas=document.getElementById("test");
var ctx=canvas.getContext("2d");
var img=document.getElementById("imgID");
ctx.drawImage(img,10,10);
assuming that your has the id #image, you could use
var img = document.getElementById("image");
var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context
img.onload = function(){
ctx.drawImage(img, 200, 200); // x, y, width, height
}
Suppose you have an <img> tag with id of image. You can obtain the image reference by using the getElementById method. Something like the following:
var img = document.getElementById("image");
Then using your code above.
You can give the image src to your new image
var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context
var img = new Image();
img.src = document.getElementById('testImage').src;
img.onload = function(){
ctx.drawImage(img, 200, 200); // x, y, width, height
}
add id to your image element
<img src='test.png' id="testImage">

Categories