Javascript: Setting Image to Canvas doesn't work right - javascript

I'm basically trying to get the selected image file from a input dialog and set it to a canvas that's in my HTML. However, the image gets cropped and only a portion of the image is shown.
Javascript:
function onSS1Change(file) {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function () {
ctx.drawImage(img, 20, 20);
}
img.src = URL.createObjectURL(file.target.files[0]);
}
HTML:
<input id="ss1-inputdiag" type="file" onchange="onSS1Change(event)" />
Fiddle: http://jsfiddle.net/tdy9tqfh/
I need to get the original height and width
What am I doing wrong?

jsFiddle : http://jsfiddle.net/CanvasCode/tdy9tqfh/2/
Just update the canvas height and width to fit the image, also you were drawing your image at position x 20 and y 20 so all your images will be slightly cut off at the right side and bottom.
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
function handleFiles(e) {
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
var img = new Image;
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function() {
c.width = img.width;
c.height = img.height;
ctx.drawImage(img, 0,0);
alert('the image is drawn');
}
}

Related

Loading image and resizing through canvas causes infinite loop

I want to get an image scaled correctly after loading it with a dummy click on a <input type='file'> and compressing it via drawing it onto a canvas. When calling a console.log() inside the img.onload I discovered it was being run in a loop. Putting the img.src = canvas.toDataURL("image/png") outside of the onload results in a blank image but no loop. Moving things around by trial and error has not been effective as I don't get the dynamics at play here (even though I can get images redrawn when rescaling a canvas). Thanks!
$('button.picture').on('click',function(){
var outerWrapper = $(this).closest('.outerWrapper')
$(this).siblings('.imageLoad').on('change', function(e){
var loadedImage = e.target.files[0]
var img = new Image();
img.src = window.URL.createObjectURL(loadedImage);
var canvas = document.createElement("canvas");
canvas.width = outerWrapper.width()
canvas.height = outerWrapper.height()
img.onload = function(e){
//still here the img.width returns the canvas width and not the original image's width
console.log(img.width)
var context = canvas.getContext("2d");
context.drawImage(img,0,0, canvas.width, canvas.height )
img.src = canvas.toDataURL("image/png")
}
$(this).closest('.outerWrapper').children('.imageWrapper').append(img)
})
$(this).siblings('.imageLoad').trigger('click')
})
To answer my own question I want to make clear what my aims were:
Load in image through a dummy click on an <input type="file">
Keeps the aspect ratio of the original image
Compress it
What worked was not setting img.src = canvas.toDataURL("image/png") as you would when resizing a canvas but by loading the original again image with URL.createObjectURL(loadedImage). To preserve the aspect ration I had to create two separate images, one to get the img.naturalWidth and img.naturalHeight for calculation and the next to load the image onto the canvas. Works a charm. Would be interested to learn where it can be refined.
$('button.picture').on('click',function(){
var outerWrapper = $(this).closest('.outerWrapper')
$(this).siblings('.imageLoad').on('change', function(e){
var loadedImage = e.target.files[0]
var img = new Image();
img.src = window.URL.createObjectURL(loadedImage);
var canvasPic = $('<canvas class="canvasPic"></canvas>')
canvasPic.prependTo(outerWrapper)
var canvas = canvasPic[0]
canvas.width = outerWrapper.width()
canvas.height = outerWrapper.height()
var context = canvas.getContext("2d");
var image = new Image();
image.onload = function(){
var w = img.naturalWidth
var h = img.naturalHeight
var ratio = h/w
var newWidth = canvas.height/ratio
context.drawImage(img,0,0,newWidth,canvas.height)
}
image.src = URL.createObjectURL(loadedImage);
})
$(this).siblings('.imageLoad').trigger('click')
})

Draw a square version of image in canvas

I am trying to show previews of uploaded images in a canvas. The preview should be a square version of image.
What I have:
var img = new Image;
img.src = imageSrc;
var c = document.getElementById('file-preview-' + data.response.id);
var ctx = c.getContext("2d");
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
And the preview:
So how can I draw on the canvas a 150x150 square with maintained ratio cropped version of the image?
For example for this image:
I should get:
Here's a method that yields precisely the result you desire, cropped, resized and centered (with commented out lines that yield a left based cropping instead)...
var ctx;
function init(event) {
ctx = document.getElementById('canvas').getContext('2d');
// Your preview is actually 120x120,
// but I've stuck with the textual description of
// your requirements here.
ctx.canvas.width = 150;
ctx.canvas.height = 150;
loadBackground('http://i.stack.imgur.com/PCKEo.png');
}
function loadBackground(path) {
var img = new Image();
img.onload = drawBackground;
img.src = path;
}
function drawBackground(event) {
var img = event.target;
var imgSize = Math.min(img.width, img.height);
// The following two lines yield a central based cropping.
// They can both be amended to be 0, if you wish it to be
// a left based cropped image.
var left = (img.width - imgSize) / 2;
var top = (img.height - imgSize) / 2;
//var left = 0; // If you wish left based cropping instead.
//var top = 0; // If you wish left based cropping instead.
ctx.drawImage(event.target, left, top, imgSize, imgSize, 0, 0, ctx.canvas.width, ctx.canvas.height);
}
window.addEventListener('load', init, false);
<canvas id="canvas"></canvas>
Based on information from this question: SO Question
I was able to modify what was done to create a square cropped image in canvas:
var img = new Image;
img.src = "http://cdn.bmwblog.com/wp-content/uploads/2016/02/M-Performance-Parts-BMW-M2-3.jpg"; //Or whatever image source you have
var c= document.getElementById('file-preview');
var ctx=c.getContext("2d");
img.onload = function(){
ctx.drawImage(img, img.width/2, img.height/2, img.width, img.height, 0, 0, img.width, img.height);
};
You just have to modify the arguments you are passing to the drawImage function as well as add some more.
You can see a fiddle here: https://jsfiddle.net/4d93pkoa/3/
Remember that the first two parameters specify the image's top left coordinates within the canvas element.
Remember to set the width and height of the canvas element in HTML to a square shape.

javascript draw a image on canvas

I try to build a javascript code, to draw a image on canvas, but I don't know where go wrong.
That is my code:
<body>
<canvas id = "my_canvas"></canvas>
<script>
function setup(){
var canvas = document.getElementById('my_canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.src = 'a.png';
ctx.drawImage(image,5,5);
};
window.onload = setup;
setup();
</script>
The question is, if I put a line of code setup(); at end then the image is correctly draw, I don't know why.
Thanks.
The problem is that image is loaded asynchronously, so if you set the source and draw it immediately then the image bits are not yet available and nothing is drawn.
You have to wait for the image to load before being able to draw it on a canvas.
Changing the code to
image.onload = function() {
ctx.drawImage(image, 5, 5);
};
image.src = "a.png";
should work as expected.
The image is loading asynchronously. This code will work:
JavaScript:
function setup(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
var image = new Image();
image.onload = function () {
ctx.drawImage(image,5,5);
};
image.src = 'a.png';
}
window.onload = setup;

How to resize the image before base64 conversion

In my sencha based application i want to convert the image into base64,Before that i want to resize the original one.Here the code which i have used to convert base64
function getBase64FromImageUrl(URL)
{
var img = new Image();
img.style.width = '5%',
img.style.height = '5%',
img.src = URL;
img.onload = function ()
{
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 10, 10);
var dataURL = canvas.toDataURL("image/jpg");
if(App.gvars.userpic=='1')
{
cdd=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
if(App.gvars.userpic=='2')
{
c=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
}
}
How to resize or redimension the image before conversion?I have tried with changing img.style.width and hieght but there is no change at all.Please help me
Per devnull69's suggestion, simply use drawImage() to resize the image when you add it into the canvas.
See the API at either W3Schools or MSDN.
You can even play with the values in a live-coding example at Html5CanvasTutorials

Loading Image into document.body Background

I'm attempting to pull an image (in this case, /camera/frame, which is a known-good JPG), and load it as the background of my document.body.
Here's my code thus far:
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
console.log("onload");
document.body.style.backgroundImage = this.src;
};
backgroundImage.src = 'camera/frame';
"onload" prints as expected, and this.src prints out the full URL to /camera/frame, however document.body.style.backgroundImage remains "".
I believe you may be missing two things.
var path = 'path/to/image.jpg';
document.body.style.background='url('+path+')';
Canvas 2D to the rescue!
var backgroundImage = new Image();
backgroundImage.onload = function ()
{
var canvas = document.getElementById('canvas');
canvas.width = this.width;
canvas.height = this.height;
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(this, 0, 0, this.width, this.height);
};
backgroundImage.src = 'camera/frame';
backgroundImage.width = $(window).width();
backgroundImage.height = $(window).height();
Loads the image in the background, then draws it into the canvas seamlessly!

Categories

Resources