drawImage resize image to 500px high - javascript

I am trying to take the image that is 1280x960 and resize it using drawImage so that is is 600 pixels high. I have worked out the ratio that I think I need to achieve this but don't know how to apply...
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = this.height;
canvas.width = this.width;
ratio = canvas.height / canvas.width;
console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
ctx.drawImage(img, 0, 0, 300, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>
How can I specify the resulting image size, making the width automatic? I eventually want this function to resize any image to 500 pixels high.

Here is a solution, a bit roundabout but seems to work. I created a new image using toDataURL() from the original sized canvas. Although the new image is reduced, the total dimension is still that of the original image, such that the remaining space is transparent. Then I set and clip this image into a new canvas. The resulting canvas has the correctly sized image which can be copied and pasted with the desired dimension.
If the snippet below does not display the image in the new canvas, please try the following fiddle which seems to work well: https://jsfiddle.net/jfeferman/u80fhy0z/
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.crossOrigin = "Anonymous";
img.onload = function () {
canvas.height = this.height;
canvas.width = this.width;
ratio = canvas.height / canvas.width;
console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
ctx.drawImage(img, 0, 0, 500 / ratio, 500);
var newImage = new Image();
newImage.crossOrigin = "Anonymous";
newImage.src = canvas.toDataURL();
var newCanvas = document.getElementById("newcanvas");
newCanvas.height = 500;
newCanvas.width = 500 / ratio;
var newCtx = newCanvas.getContext('2d');
newCtx.drawImage(newImage, 0, 0, 500 / ratio, 500, 0, 0, 500 / ratio, 500);
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
#mycanvas {
display: none;
}
<canvas id="newcanvas"></canvas>
<canvas id="mycanvas"></canvas>

I applied the ratio to your call to drawImage and it seems to work:
ctx.drawImage(img, 0, 0, 500 / ratio, 500);
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = this.height;
canvas.width = this.width;
ratio = canvas.height / canvas.width;
console.log(canvas.width + 'x' + canvas.height + ' | ratio = ' + ratio);
ctx.drawImage(img, 0, 0);
canvas.style.width = 500 / ratio + "px";
canvas.style.height = 500 + "px";
}
img.src = 'https://c.slashgear.com/wp-content/uploads/2015/06/dxo-one-sample-3-1280x960.jpg';
<canvas id="mycanvas"></canvas>

Related

Javascript crop and scale image to be 300 pixel

I want to know how we can scale and crop an image in Javascript. I want to scale it down to 300x300px and crop it a little.
Do you have any suggestions ? I have the following code :
function cropImage(imagePath, newX, newY, newWidth, newHeight) {
//create an image object from the path
var img = document.createElement('img');
img.src = "data:image/png;base64,"+imagePath;
//alert(img.width);
//alert(img.height);
//initialize the canvas object
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
//set the canvas size to the new width and height
canvas.width = 300;
canvas.height = 300;
//draw the image
ctx.drawImage(img, newX, 75, 300, 300, 0, 0, 300, 300);
variables.imageCrop = canvas.toDataURL();}
Thank you !
Try it:
And learn more about .drawImage()
function cropImage(imagePath, leftRight, topBottom, newWidth, newHeight) {
const img = document.createElement('img');
img.src = imagePath;
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
img.addEventListener('load', function() {
//Set your canvas size as your choice
//here i just scaled by 10 with original dimension
canvas.width = img.naturalWidth*10;
canvas.height = img.naturalHeight*10;
const cropLeft = leftRight[0];
const cropRight = img.naturalWidth - leftRight[0] - leftRight[1];
const cropTop = topBottom[0];
const cropBottom = img.naturalHeight - topBottom[0] - topBottom[1];
ctx.drawImage(
img,
cropLeft,cropTop,
cropRight, cropBottom,
0,0, //here you can control placement of cropped image from left and top, by default it stays in 0,0 meaning the top left corner of the canvas
newWidth,newHeight //new width and height of cropped image
);
});
}
//Size of this image is 100x100 px
const img = "https://dummyimage.com/100.png/09f/fff";
//here [10,10] meaning crop 10px from left and 10px from right
//here [20,20] meaning crop 20px from top and 20px from bottom
cropImage(img,[10,10],[20,20], 100, 100);

canvas down Sizing the image is getting higher size

Im resizing the image size to make it smaller im taking 20% of the height and 20% of the width. but im getting wrong result is getting me a higher size of an image.
function imageToDataUri(img, width, height) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL();
}
imageToAdjust = 'data:image/png;base64,' + window.btoa(e.target.result);
var img = new Image;
img.onload = resizeImage;
img.src = imageToAdjust;
function resizeImage() {
console.log(img.width);
console.log(img.height);
var x = img.width - (0.2 * img.width);
var y = img.height - (0.2 * img.height);
console.log(x);
console.log(y);
var newDataUri = imageToDataUri(this, x, y);
console.log(newDataUri);
var base64 = newDataUri.match(/data:(.+);base64,(.+)/);
console.log('after resizing');
console.log(base64);
var base64Number = Math.round((base64[2].length )*3/4) ;
console.log(base64Number);
}
what im getting through console.logs is for example i have image with size is 5663096 width 4032 and height 3024 then after i take 20% off im getting it width 3225.6 and height 2419.2 which is correct. but after i call imageToDataUri(this, x, y); function the image size will be 12031242 which is double. it should be smaller than 5663096

How to stretch image in canvas?

I need to stretch my image to the top and to the bottom in canvas.
How can I do this?
Here's the codepen
HTML
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
</canvas>
JS
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
ctx.drawImage(img, 10, 10);
}
drawImage allows you to pass the width and height as third and fourth parameter.
So your last line should be ctx.drawImage(img, 0, 0,c.width, c.height); in order to fill the entire canvas.
If you just want an image to stretch to fill in the height you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
ctx.fillStyle = "#000";
ctx.fillRect(0,0,c.width,c.height);
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
img.onload = function () {
ctx.drawImage(img, (c.width / 2) - (img.width / 2), 0, img.width, c.height);
}
However the link you provided basically just zooms into the image.
So you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/2/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
var zoom = 1.0;
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
setInterval(function () {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, c.width, c.height);
ctx.drawImage(img, (c.width / 2) - ((img.width * zoom) / 2), (c.height / 2) - ((img.height * zoom) / 2),
img.width * zoom,
img.height * zoom);
}, 1);
document.getElementById("zoomIn").onclick = function () {
zoom += 0.1;
};
document.getElementById("zoomOut").onclick = function () {
if (zoom > 0.1) {
zoom -= 0.1;
}
};
Here is a more detailed answer of how to fill or fit a canvas while also keeping the image aspect.
Fill canvas

How can I cut an image at a 45 degree angle using Javascript?

Basically I need to reduce the size of an image and cut it to be a triangle. How would I do this using javascript?
This is approximately what I am looking to accomplish (obviously it would be a straight line, but that's the best I could do in paint):
Here's the code I have so far:
HTML: <div id = "mydiv"></div>
Javascript:
document.getElementById("mydiv").onclick = moulding_change('5f52a13c425655fa62058418542b95ca');
function moulding_change(thumb)
{
var ppi = 15;
var SITE_URL = "http://www.asa.tframes.org:1881";
var img = new Image();
img.src = SITE_URL + '/system/components/compimg/' + thumb + '/pattern';
img.onload = function() {
console.log("width before " + this.width);
//width needs to be the same as the height (in this case 450)
img.width = img.height / ppi;
//img.width = img.height;
img.height /= ppi;
console.log("width after " + this.width);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
canvas.style.position = "absolute";
canvas.style.zIndex = 5;
canvas.style.width = "1000px";
canvas.style.height = "1000px";
// Save the state, so we can undo the clipping
ctx.save();
// Create a shape, of some sort
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(img.width,0);
ctx.lineTo(img.width,img.width);
ctx.closePath();
// Clip to the current path
ctx.clip();
ctx.drawImage(img, 0, 0);
// Undo the clipping
ctx.restore();
$("#mydiv").append(canvas);
};
}
Thanks to Geoff, I was able to create canvas elements. The problem ended up being that I wasn't specifying a width, height for the image.

javascript - Why does this canvas image not rotate correctly?

Why does this canvas image not rotate correctly?
When I click the rotate button the image rotates but gets cropped weirdly. I want the image to stay intact and simply rotate.
Important: I'm not looking to rotate the div, I'm looking to rotate the actual image.
See fiddle:
http://jsfiddle.net/8V4V7/2/
Code:
function rotateBase64Image(base64data, callback) {
console.log("what we get: " + base64data);
var canvas = document.getElementById("dummyCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = base64data;
image.onload = function() {
ctx.translate(image.width, image.height);
ctx.rotate(Math.PI);
ctx.drawImage(image, 0, 0);
callback(canvas.toDataURL());
};
}
EDIT:
I need the image to rotate by 90 degrees on every click.
I tried the following but it doesn't work:
ctx.rotate(Math.PI/2);
This worked for me (I specified the height and width of the canvas inside the onload function):
function rotateBase64Image(base64data, callback) {
console.log("what we get: " + base64data);
var canvas = document.getElementById("dummyCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = base64data;
image.onload = function () {
canvas.height = image.height;
canvas.width = image.width;
ctx.translate(image.width, image.height);
ctx.rotate(Math.PI);
ctx.drawImage(image, 0, 0);
callback(canvas.toDataURL());
};
}
Edit
Updated function to rotate 90 degrees with every click (remove i in i*Math.PI to rotate 90 degrees only once)
var i = 0;
function rotateBase64Image(base64data, callback) {
console.log("what we get: " + base64data);
var canvas = document.getElementById("dummyCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = base64data;
image.onload = function() {
canvas.width = image.height;
canvas.height = image.width;
ctx.translate(canvas.width / 2, canvas.height / 2);
i++;
ctx.rotate(i*Math.PI/2);
ctx.translate(-canvas.width / 2, -canvas.height / 2);
ctx.drawImage(image, 0, 0);
};
}
Updated Fiddle
Just some supporting info for rotations, notably the saving of the context and how to rotate around the center of the image.
var context = canvas.getContext('2d');
//save the context
//pushes a Matrix on the transformation stack
context.save();
context.translate(x, y); //where to put image
context.rotate(angle); //angle in degrees (i think...)
context.scale(scale); //optional scale
//rotate around center of image
context.drawImage(bitmap, -image.width / 2, -image.height / 2);
//or rotate around top left corner of image
context.drawImage(image, 0, 0);
//restore the canvas
//pop a matrix off the transformation stack
context.restore();
References:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations
http://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/

Categories

Resources