html5 canvas with image: save original imagesize - javascript

I need to extract original image-size canvas, but canvas must be always the same width and height, and if image aspect ration is different, it must be centered in canvas. What i mean i will explain by schema:
gray - all canvas area, over it (inner) - image
here you could preview it:
http://plnkr.co/edit/IBE35kJqNM3tSI8J3BqL?p=preview
$(function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var img = new Image();
img.onload = start;
img.setAttribute('crossOrigin', 'anonymous');
img.src = "https://dl.dropboxusercontent.com/u/59666091/Audi-RS7-Sportback-1.jpg";
function start() {
var MAX_WIDTH = 400;
var MAX_HEIGHT = 310;
var iw = img.width;
var ih = img.height;
var scale = Math.min((MAX_WIDTH / iw), (MAX_HEIGHT / ih));
var sw = iw * scale;
var sh = ih * scale;
ctx.drawImage(img,
0, 0, iw, ih, (canvas.width - sw) / 2, (canvas.height - sh) / 2, iw * scale, ih * scale
);
console.log(canvas.toDataURL('image/jpeg', 100));
}
});
and all is ok, except one thing: when i execute canvas.toDataURL('image/jpeg', 100) i get only 400*310px image, but i need originial-size (much bigger then 400*310px) canvas-based data image, with background borders (as gray on schema etc).
is it real to do? and how, without loosing any current functionality?

You need change canvas width,height and drawing on the canvas max width and height
http://plnkr.co/edit/hycPgkjbT5YCzZPN3Rrm?p=preview
$(function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var img = new Image();
img.onload = start;
img.setAttribute('crossOrigin', 'anonymous');
img.src = "https://dl.dropboxusercontent.com/u/59666091/Audi-RS7-Sportback-1.jpg";
function start() {
var MAX_WIDTH = img.width;
var MAX_HEIGHT = img.height;
var iw = img.width;
var ih = img.height;
$('#canvas').attr('width', img.width);
$('#canvas').attr('height', img.height);
var scale = Math.min((MAX_WIDTH / iw), (MAX_HEIGHT / ih));
var sw = iw * scale;
var sh = ih * scale;
ctx.drawImage(img,
0, 0, iw, ih, (canvas.width - sw) / 2, (canvas.height - sh) / 2, iw * scale, ih * scale
);
console.log(canvas.toDataURL('image/jpeg', 100));
}
});

Related

return canvas as webp image

How can I return the canvas on this function as webp image?
function capture(video) {
if(scaleFactor == null){
scaleFactor = 1;
}
//var w = video.videoWidth * scaleFactor;
//var h = video.videoHeight * scaleFactor;
var w = 700;
var h = 400;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var uniq = 'img_' + (new Date()).getTime();
canvas.setAttribute('id', uniq);
return canvas ;
}
Canvas has a method known as .toDataURL(type, encoderOptions).
I this case the following snippet should suffice
canvas.toDataURL('image/webp');
This will give you a data url which is a base64 encoding of the image and will look something like
data:image/webp;base64,UklGRqgCAABXRUJQVlA4WAoAAAAwAAAAxwAAYwAASUNDUBgCAAAAAAIYAAAAAAQwAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlkZXNjAAAA8AAAAHRyWFlaAAABZAAAABRnWFlaAAABeAAAABRiWFlaAAABjAAAABRyVFJDAAABoAAAAChnVFJDAAABoAAAAChiVFJDAAABoAAAACh3dHB0AAAByAAAABRjcHJ0AAAB3AAAADxtbHVjAAAAAAAAAAEAAAAMZW5VUwAAAFgAAAAcAHMAUgBHAEIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFhZWiAAAAAAAABvogAAOPUAAAOQWFlaIAAAAAAAAGKZAAC3hQAAGNpYWVogAAAAAAAAJKAAAA+EAAC2z3BhcmEAAAAAAAQAAAACZmYAAPKnAAANWQAAE9AAAApbAAAAAAAAAABYWVogAAAAAAAA9tYAAQAAAADTLW1sdWMAAAAAAAAAAQAAAAxlblVTAAAAIAAAABwARwBvAG8AZwBsAGUAIABJAG4AYwAuACAAMgAwADEANkFMUEgPAAAAAQcQEREAUKT//yWi/6lwAFZQOCBSAAAA8AcAnQEqyABkAD5tNplJpCMioSBoAIANiWlu4XXwADuh1VJsmIdVSbJiHVUmyYh1VJsmIdVSbJiHVUmyYh1VJsmIdVSbJhYAAP7/wbAAAAAAAA==
More information for this can be found on https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

drawImage resize image to 500px high

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>

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

Canvas draw new image from daturl

I'm using the function below to resize and image using canvas
var img = new Image();
img.src = reader.result;
img.onload = function() {
var max_width = 800;
var max_height = 800;
var tempW = img.width;
var tempH = img.height;
var aspect_ratio = 1;
if (tempW > tempH) {
if (tempH > max_height){
var aspect_ratio = tempH / max_height
}
} else {
if (tempW > max_width){
var aspect_ratio = tempW / max_width
}
}
tempH = tempH / aspect_ratio;
tempW = tempW / aspect_ratio;
var canvas = document.createElement('canvas')
canvas.id = "uploadedcanvas";
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.fillStyle="#FFFFFF";
ctx.fillRect(0,0,tempW,tempH);
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas)
}
This is able to resize an image from taken from file reader. I would like to create a second image in the same canvas using the dataURL as the image source but this it does not seem to work this is what I'm doing
function createsecondimage(dataURL,tempW,tempH,max_width,max_height,canvas){
var copy = document.createElement('canvas');
copy.width = max_width;
copy.height = max_height;
var copyctx = copy.getContext("2d");
var sx = (tempW - max_width) / 2
var sy = (tempH - max_height) /2
copyctx.fillStyle="#FFFFFF";
copyctx.fillRect(0,0,max_width,max_height);
var imgcopy = new Image();
imgcopy.src = dataURL;
imgcopy.onload = function() {
copyctx.drawImage(imgcopy, sx, sy, 800, 800,0, 0, 800, 800);
var dataURL_ = copy.toDataURL("image/jpeg");
}
However datURL_ appears to be empty. I'm not sure why this is the case. Ideally I would want to create a new image using the image that was just resized.
You can do the following two changes and it should work:
set imgcpy.src after onload.
Use copyctx.drawImage(this, ...) instead of imgcopy.
This way you are making sure decoding and setting of image is not completed before onload is called, and this will have a valid reference to the image being decoded.

Image scaling works locally but not when ran from server

I am trying to scale images when loaded into the browser. Here is my code that I am working with -
function importImage(e) {
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
var reader = new FileReader;
reader.onload = function(event) {
event.preventDefault();
var img = new Image;
img.src = event.target.result;
img.onload = function() {
width = img.width;
height = img.height;
var scaleX, scaleY, scale;
var scaledWidth, scaledHeight;
scaleX = width / canvas.width;
scaleY = height / canvas.height;
scale = scaleX > scaleY ? scaleX : scaleY;
scaledWidth = width / scale;
scaledHeight = height / scale;
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.drawImage(img, (canvas.width - scaledWidth) / 2, (canvas.height - scaledHeight) / 2, scaledWidth, scaledHeight);
}
}
reader.readAsDataURL(e.target.files[0]);
}
It seems to works ok when used from a local machine but when it is ran from the server the scaling doesn't work. I assume it is to do with how I am referring to the actual image but I am unsure.

Categories

Resources