How the canvas manage the ratio of the image - javascript

All:
I wonder if I draw a image on canvas, if the image ratio is not fit the canvas, how does canvas scale it( suppose only width and height set on canvas)?
For example:
<canvas id="myCanvas" style="width:200px; height:200px;"></canvas>
<script>
var canvas = d3.select("#myCanvas").node();
var context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
console.log(img.naturalWidth, img.naturalHeight);
context.drawImage(img, 0, 0);
}
img.src = "https://www.google.com/images/srpr/logo11w.png";
</script>
The result seems that the image has been stretch a little bit vertically and squeeze horizontally, I want to know why canvas deal it in that way and how to draw it as it is or scale in its ratio like ?
I also tried giving width and height when draw the image, but it still seems not quite right, for example:
// in this way, the image still get stretched and squeeze
<script>
var canvas = d3.select("#myCanvas").node();
var context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
console.log(img.naturalWidth, img.naturalHeight);
context.drawImage(img, 0, 0, img.naturalWidth/5, img.naturalHeight/5);
}
img.src = "https://www.google.com/images/srpr/logo11w.png";
</script>
OR
// Even I give it a 100 by 100 size, it can not do it that way
<script>
var canvas = d3.select("#myCanvas").node();
var context = canvas.getContext("2d");
var img = new Image();
img.onload = function(){
console.log(img.naturalWidth, img.naturalHeight);
context.drawImage(img, 0, 0, 100, 100);
}
img.src = "https://www.google.com/images/srpr/logo11w.png";
</script>
Thanks

The bitmap of the canvas is by default 300x150 independent of the CSS size.
<canvas id="myCanvas" style="width:200px; height:200px;"></canvas>
This will stretch anything drawn to the 300x150 bitmap to fit 200x200 CSS size.
Use canvas' attributes (or properties from JavaScript) to set the size properly:
<canvas id="myCanvas" width=200 height=200></canvas>

Related

HTML/Javascript Canvas drawImg Function

I am trying to mirror a section of an image, into a below canvas, of exactly the same size, based on fixed values. For example, present it a picture of a map, and mirror below in the same position and the same size a building on that original map image. However, for some unknown reason, it resizes the mirrored section every time? The only botch fix for this is to apply a multiplier to all "d" variables in the draw image function, as seen here: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
Any ideas as to why this is?
Code (minus the multiplier, multipler avaliable if needed):
<!DOCTYPE html>
<html>
<body>
<img id="scream" src="image1.jpg" alt="The Scream" width="100%" height="100%">
<!--<canvas id="myCanvas" style="border:1px solid #d3d3d3;">-->
Your browser does not support the HTML5 canvas tag.
<script>
document.getElementById("scream").onload = function() {
var c = document.createElement('canvas');
var imgData = document.getElementById("scream");
c.width = imgData.width;
c.height = imgData.height;
var body = document.getElementsByTagName("body")[0];
body.appendChild(c);
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
console.log(img);
//ctx.drawImage(img, 0, 0);
//ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
ctx.drawImage(img, 200, 200, 100, 143, 200, 200, 100*1.87, 143*1.87);
//console.log(ctx);
};
</script>
<p><strong>Note:</strong> The canvas tag is not supported in Internet
Explorer 8 and earlier versions.</p>
</body>
</html>
In order to mirror the image you need to translate the context ctx.translate(0, this.height) and then scale it ctx.scale(1,-1);. However on resize the canvas will stay the initial size while the image will adapt to the window size. If you need the canvas to adapt as well you will need to recalculate everything on resize.
var imgData = document.getElementById("scream");
imgData.onload = function() {
var c = document.createElement('canvas');
c.width = this.width;
c.height = this.height;
var body = document.getElementsByTagName("body")[0];
body.appendChild(c);
var ctx = c.getContext("2d");
ctx.translate(0, this.height);
ctx.scale(1,-1);
ctx.drawImage(this, 0, 0,this.width,this.height);
};
<img id="scream" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/imgres.jpg" alt="The Scream" width="100%" height="100%">
Next comes an example where the canvas size changes on resize. In this case you need to move all the code that draws the image inside a function to be called on resize.
Quote from MDN:
Since resize events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame, setTimeout or customEvent"
window.onload = function() {
var imgData = document.getElementById("scream");
var c = document.createElement("canvas");
var body = document.getElementsByTagName("body")[0];
body.appendChild(c);
var ctx = c.getContext("2d");
imgData.onload = function() {
init();
};
function init() {
c.width = imgData.width;
c.height = imgData.height;
ctx.translate(0, imgData.height);
ctx.scale(1, -1);
ctx.drawImage(imgData, 0, 0, imgData.width, imgData.height);
}
setTimeout(function() {
init();
addEventListener("resize", init, false);
}, 15);
};
<img id="scream" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/imgres.jpg" alt="The Scream" width="100%" height="100%">
This is because you are using the ImageElement's .width and .height properties. At getting, these should return the computed value of their corresponding attribute, in px.
In the markup, these attributes have both been set to the relative value 100%, which means their computed value will be relative to the ImageElement's parent's size.
So when you ask drawIamge to draw your image using these output size, it will indeed resize / stretch your image. To avoid it, you need to use the original size of the image, not of the ImageElement.
To do so, if all you need is to draw at the same size as the original image, then you can simply call the length 3 version of drawImage(source, x, y), which will use by default the source's original size.
But you'll still need to resize your canvas to the correct size before doing it, and to do this, you need to access the image's original size.
Fortunately, this original size of the image, is available from the ImageElement's naturalWidth and naturalHeight properties.
document.getElementById("scream").onload = function() {
var c = document.createElement('canvas');
var imgData = document.getElementById("scream");
console.log('computed width: ', imgData.width);
console.log('original width: ', imgData.naturalWidth);
c.width = imgData.naturalWidth;
c.height = imgData.naturalHeight;
var body = document.body;
body.appendChild(c);
var ctx = c.getContext("2d");
// the 3 length version is enough here
ctx.drawImage(imgData, 0, 0);
};
<img id="scream" src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Edvard_Munch_-_The_Scream_-_Google_Art_Project.jpg/190px-Edvard_Munch_-_The_Scream_-_Google_Art_Project.jpg" alt="The Scream" width="100%" height="100%">

HTML 5 Canvas] Image quality when I resize

thank you for taking a look.
What I am trying to do here is... load image from computer (by using FileReader), put img tag's src to the file. Then draw canvas with that image.
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onload = function () {
preview.src = reader.result;
drawCanvas();
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "sample.jpg";
}
}
previewFile(); //calls the function named previewFile
window.onload = function () {drawCanvas(); };
function drawCanvas() {
var img = document.querySelector("img");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
ctx.filter = window.getComputedStyle(document.querySelector("img")).filter;
ctx.drawImage(img, 0, 0);
}
Problem is when I load another image file. It loads in the canvas, but not fit in the canvas size. It keeps the original image size and "part" of the image is shown in the canvas.
In order to solve it, I tried following:
ctx.drawImage(img, 0, 0, document.getElementById('canvas').width,
document.getElementById('canvas').height);
It works, however the image quality becomes really bad... since it is not original image size. It is adjusted to the certain height and forced to be resized.
All I want to do is... keep the original canvas size (width: some px; height: auto), so when I load the image, it fits to the canvas width and adjusted height.
Would you please help me? Thank you.
Added
I researched myself and found following:
I came up with an idea - change the image size first based on the current width of the canvas.
var img = document.querySelector("img");
var canvas = document.getElementById("image");
var ratio = img.height / img.width;
img.width = canvas.offsetWidth;
img.height = img.width * ratio;
Then draw with the edited image.
var ctx = canvas.getContext('2d');
ctx.filter = window.getComputedStyle(img).filter;
ctx.drawImage(img, 0, 0, img.width, img.height);
Then I found the problem. I checked "img.height" variable is 199px. But canvas's height becomes 150px somehow. I checked and there is no css applied to the canvas at all.
So this time, I set canvas width, before drawImage().
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
ctx.filter = window.getComputedStyle(img).filter;
ctx.drawImage(img, 0, 0);
And again, the original image coming back... and "part" of the image is shown in the canvas. The canvas's size is what I wanted though...
Thank you so much for taking a look the issue. Especially #Kaiido who tried to help. Thank you. I am really new to this stackoverflow... so I didn't know how to create demo.
I found the solution. Well... it was really basic knowledge of the Canvas,,, but I think many people will forget / miss following:
var ctx = canvas.getContext('2d');
ctx.canvas.width = 1000;
ctx.canvas.height = 1000;
ctx.drawImage(img, 0, 0, 800, 800);
ctx.canvas.width is canvas's width. ctx.canvas.height is canvas's height.
In drawImage, those 800s are width and height of the image will be drawn, not the canvas's size!! So if you set... let's say 1000, 1000 in drawImage, the image will be resized to the size and it will be drawn into the canvas. If it is bigger than the canvas size, it will show only "part" of your image.
So what I did was... get the div width size where I want to put my canvas. Then calculate the ratio of the image first ( ratio = image's height / image's width ). Then set canvas size to following ( ctx.canvas.width = div width size, ctx.canvas.height = div width size * ratio ). Then draw canvas with canva's width and height ( ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height) ).
Hope this helps someone new like me :) Thank you.
This is pretty simple!
try this.
getting the ratio, setting the height, drawing the image
var ratio = img.naturalWidth / img.naturalHeight;
var width = canvas.width;
var height = width / ratio;
ctx.drawImage(img, 0, 0, width, height);
this worked for me, try this.
see the line
var width = canvas.width;
you can replace the canvas.width by any other value.

Canvas wont display image inside of it

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="spriteCanvas" width="500" height="500">
<img id="coin" width="440" height="40" src="coin.png">
</canvas>
</body>
</html>
I tried placing an image inside a canvas element, but it won't display on the browser. I know the image tag works because it's displayed if I place it outside of the canvas element. Also, if I inspect the canvas element, I can see that the image is inside, but its dimensions are 0 by 0. Can somebody explain why this isn't working?
EDIT: My original code added the image through javascript, but it wouldn't show on the canvas. It was giving me the same problems as above. But I just realized I was missing "onload".
original code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
function init() {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
init();
editted code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
coinImage.onload = function () {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
This isn't how a <canvas> tag works. If you want your image to appear in your canvas, you will have to use JavaScript to place the pixels of the image into your canvas.
<canvas>s are exactly what they state: canvases. They are an element for you to draw on programmatically. If you just want to display an image on a page, you don't need a canvas, you just need the <img> tag. In fact, elements should not be placed in <canvas>.
Take a look at CanvasRenderingContext2D.drawImage() and this tutorial: HTML5 Canvas Image Tutorial.
And this snippet:
var canvas = document.getElementById("painting"),
ctx = canvas.getContext("2d"),
image = new Image();
image.onload = function() {
ctx.drawImage(image, 30, 50);
};
image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>
To draw an image on a canvas, use the following method:
drawImage(image,x,y)
If the image you want to draw is not in the DOM already you can load an image directly from a URL with a few lines of javascript.
function loadAndDrawImage(url)
{
// Create an image object. This is not attached to the DOM and is not part of the page.
var image = new Image();
// When the image has loaded, draw it to the canvas
image.onload = function()
{
// draw image...
}
// Now set the source of the image that we want to load
image.src = url;
}
loadAndDrawImage("http://www---.png");

Image on Canvas is drawn larger than original size

On load of my image I:
var img = new Image();
img.src = e.target.result;
var canvas = $('#test-canvas')[0];
$('#test-canvas').width(img.width);
$('#test-canvas').height(img.height);
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
But the image is drawn larger than it's original size? I've tried a few images, same problem.
What's the fix?
jQuery will resize the element through CSS, which won't actually change the canvas internal height and width. This will resize the actual canvas element.
var canvas = document.GetElementById('test-canvas');
canvas.width = img.width;
canvas.height = img.height;
jsFiddle (http://jsfiddle.net/L0drfwgL/) just show it drawing it to scale, and resizing the canvas item itself.
It looks like you are pulling the image from an image element on load. You can use the src from the image element rather than recreating an image object and then get the image width/height from the element to draw the image to canvas.
<script>
$(document).ready(function(){
$('#testImg').on('load',function(){
var image = document.getElementById('testImg');
var canvas = document.getElementById('test-canvas');
canvas.width = image.width;
canvas.height = image.height;
var ctx=canvas.getContext("2d");
ctx.drawImage(image,0,0);
})
});
</script>
/** with vue3 -(to fix drawing canvas image is larger than actual image size **/
const captureImage = () => {
let width = video.value.getBoundingClientRect().width;
let height = video.value.getBoundingClientRect().height;
let context = canvas.value.getContext('2d')
canvas.value.width = width
canvas.value.height = height
context.drawImage(video.value, 0, 0, width, height)
}

Using canvas to draw image at true size

I'm trying to load an image from a URL into a HTML canvas at a 1:1 scale. I load the image, and set the canvas DOM element to the appropriate dimensions, but for some reason the image in the canvas is significantly upscaled and therefore only the top left hand corner is drawn.
This is demonstrated by the following JSFiddle: http://jsfiddle.net/KdrYr/1/
var img = new Image();
var cv = document.getElementById('thecanvas');
img.src = 'http://www.photographyblogger.net/wp-content/uploads/2009/12/Picture-in-a-picture4.jpg';
img.onload = function() {
var ctx = cv.getContext('2d');
cv.style.width = img.width + 'px';
cv.style.height = img.height + 'px';
ctx.drawImage(img, 0, 0);
};
For example, I'm trying to draw this (sorry about the big images :/)
But end up with this
What could be causing this?
You need to assign the canvas actual width and height, not via its style:
cv.width = img.width;
cv.height = img.height;
Live test case.
As for the why, well, it's explained already here.

Categories

Resources