Canvas drawImage size is wrong [duplicate] - javascript

I don't get why the following pieces of code produce different results, because css would scale the canvas as it was zoomed in,
<style>
#canvas {
width: 800px;
height: 600px;
}
</style>
<canvas id="canvas"></canvas>
In contrast with this approach (that works as expected):
<canvas id="canvas" width="800px" height="600px"></canvas>

Think about what happens if you have a JPG that is 32x32 (it has exactly 1024 total pixels) but specify via CSS that it should appear as width:800px; height:16px. The same thing applies to HTML Canvas:
The width and height attributes of the canvas element itself decide how many pixels you can draw on. If you don't specify the height and width of the canvas element, then per the specs:
"the width attribute defaults to 300, and the height attribute defaults to 150."
The width and height CSS properties control the size that the element displays on screen. If the CSS dimensions are not set, the intrinsic size of the element is used for layout.
If you specify in CSS a different size than the actual dimensions of the canvas it must be stretched and squashed by the browser as necessary for display. You can see an example of this here: http://jsfiddle.net/9bheb/5/

The explanation is here: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width as seen in another post, thanks!
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

The best way to size your canvas is to include in a div and style your div with the size that you want.
Here is the CSS
<style>
#divCanvas{
width: 800px;
height: 600px;
}
</style>
Here is the HTML
<div id="divCanvas">
<canvas id="canvas"></canvas>
</div>

Related

Scale HTML image width and height in %

I know that width and height property of HTML images can be set simply by <img src="Debian.jpg" style="height: 120px; width: 130px">.
What I am looking for is if there exists a single CSS property that takes only one value in % and scales the width and height of the original image according to that percentage. For example, if the height and width of Debian.jpg are 1000x700 and I specify 50% in that CSS property then the image scales down to 500x350 and hence the aspect ratio is maintained.
It's very hard for me to maintain the aspect ratio of the image while adjusting the height and width separately. If a property like that does not exist then is there any way to maintain the aspect ratio and achieve desirable dimensions of the image?
Yes, there is a way to maintain the image's aspect ratio and resize the image to a fraction of its original size. However, CSS cannot know the intrinsic size (the original size) of the image. Therefore, you can only do two things:
Tell the CSS explicitly the original size
Use JS to get the original size upon image load
What doesn't work
Using percentage value as the width value for img doesn't work simply because percentage value resolves to, well, a percentage of its container size, not its original size. Below, I demonstrated the not-working examples.
That being said, I personally usually want to specify the width of the image explicitly. For example, on large devices, I want the image to be 1080px. On smaller devices, I want the image to be 560px. I can simply make a container for the image of an explicit size, place the image inside the container, and specify the image's width to 100% (of its container size).
What works
As mentioned, there are two ways to make an image 50% of its original width. First, using JS. Second, tell the CSS explicitly the original image width.
Using the JS approach, you simply need to change the width of the image. Upon load, get the intrinsic width of the image, then set the new width to the intrinsic width divided by 2. Simple.
Using the telling-CSS-explicitly approach is less advantageous. This solution presumes that the image will always be the same and needs you, the developer, to know the original image size beforehand. When you change the original image size, you will also need to update your code. That being said, you can achieve this by specifying a CSS custom property inside the CSS class, specifying an attribute (in HTML) that gives the intrinsic width then using attr() (still experimental and mostly not supported), or using an intrinsicsize attribute and set the width and style through CSS (still experimental and not supported). The last two solutions, as mentioned, are not supported by most browsers and may not work properly yet.
In my opinion, your best bet to set an image's width to 50% its intrinsic width is by using JS. Here's a solution demonstrating the what-doesn't-work solutions and the JS solution. Aspect ratio is automatically maintained if you only change one of the image's size (width/height).
const imageJS = document.querySelector('.image--changed-with-js')
imageJS.onload = () => {
const intrinsicWidth = imageJS.width
imageJS.width = imageJS.width / 2
}
* {
box-sizing: border-box;
}
body,
html {
margin: 0px;
}
img {
margin: 20px 0;
}
/* Image has its intrinsic size (i.e. the original image size) */
.image--original {
width: auto;
}
/* Image contained within a 500px container
Image has a width of 50% of 500px = 250px */
.container {
width: 500px;
}
.image--changed-with-container {
width: 50%;
}
/* Image is not contained within a div
However, image is inside body
<body> is its container
It now has a width of 50% of the body
NOT 50% of its intrinsic width */
.image--changed-without-container {
width: 50%;
}
/* Image changed using JS
You can get the intrinsic size through JS and modify its size there */
.image--changed-with-js {}
<img class="image--original" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
<div class="container">
<img class="image--changed-with-container" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
</div>
<img class="image--changed-without-container" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
<img class="image--changed-with-js" src="https://img.freepik.com/free-vector/abstract-galaxy-background_1199-247.jpg?size=626&ext=jpg">
If you set the width to a fixed number of pixels, e.g. img { width: 500px; }, the height will adjust accordingly to maintain the same aspect ratio. If you set the height, the width will adjust accordingly to maintain the same aspect ratio.
If you set the width to a percentage, e.g. img { width: 50% }, the browser will assume you mean a percentage of the element's container. The height will adjust accordingly to maintain the same aspect ratio.
However, if you set the height to a percentage, e.g. img { height: 50% }, that just won't work for various reasons.
The solution is really simple. To preserve the aspect ratio, all you need to do is set the height and width CSS properties like:
#theImage {
width: 100%;
height: auto;
}
<img id="theImage" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg">
By setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained. The end result is an image that scales up or down perfectly.
The downside of this solution is that a single image cannot effectively display across the range of resolutions on which your content may be viewed. For a more comprehensive solution, you need to bring in media queries and images of varying sizes to replace a lower resolution image when the time is right
My suugestion is to remove the specified sizes you put. Yes there is a code that can be specified in css.
in html do like that:
<img src="Debian.jpg" alt="Debian Image" class="myCustomImages">
in css do something like that:
.myCustomImages {
max-width: 50%;
max-height: 50%;
}
So as I understand, You want to keep the image aspect-ratio while defining it's scale in percentage of the original size. Below is my suggestion:
When the image is inside a container with display: inline-block, you can define a width for an image in css, and it will be relative to itself (if the parent have display: block it will be relative to it's parent, if it's display:inline it will be relative to the nearest block parent).
When you define one of the dimentions (width or height) and not the other, by default it's keep the aspect ratio.
So what I suggest to do is wrap the image in an inline-block parent, and define only width in a percentage. like this:
div {
display: inline-block;
}
#half {
width: 50%;
}
#original {
width: 100%;
}
#big {
width: 150%;
}
<h1>Image 400X267</h1>
<h3>50% size</h3>
<div>
<img id="half" src="https://bloximages.newyork1.vip.townnews.com/unionleader.com/content/tncms/assets/v3/editorial/f/f4/ff44150d-01ca-5e2d-8f7d-9d17e9faadd4/5dfa95339e09c.image.jpg?resize=400%2C267"/>
</div>
<h3>100% size</h3>
<div>
<img id="original" src="https://bloximages.newyork1.vip.townnews.com/unionleader.com/content/tncms/assets/v3/editorial/f/f4/ff44150d-01ca-5e2d-8f7d-9d17e9faadd4/5dfa95339e09c.image.jpg?resize=400%2C267"/>
</div>
<h3>150% size</h3>
<div>
<img id="big" src="https://bloximages.newyork1.vip.townnews.com/unionleader.com/content/tncms/assets/v3/editorial/f/f4/ff44150d-01ca-5e2d-8f7d-9d17e9faadd4/5dfa95339e09c.image.jpg?resize=400%2C267"/>
</div>

How can i change default max canvas size?

I saw on the Internet the different max size and area of a canvas. I would like to change them for my project because i create canvas of 5000px / 2600px. I test to put a smaller canvas (300px / 300px) and it works i've no error (NS_ERROR_FAILURE)
Thank's all
Canvas size is device dependent. Have a look at Maximum size of a <canvas> element, this may help you to resolve the issue.
You may use CSS for that, in your webpage.
<head>
<style>
canvas{
width: 300px;
height: 300px;
}
</style>
</head>
You can't change the maximum canvas size supported by a browser, but you can detect it and avoid creating canvas elements that exceed the browser's size limitations.
See my answer in the Maximum size of a <canvas> element thread for details.

HTML Pixel Draw Thingy [duplicate]

I don't get why the following pieces of code produce different results, because css would scale the canvas as it was zoomed in,
<style>
#canvas {
width: 800px;
height: 600px;
}
</style>
<canvas id="canvas"></canvas>
In contrast with this approach (that works as expected):
<canvas id="canvas" width="800px" height="600px"></canvas>
Think about what happens if you have a JPG that is 32x32 (it has exactly 1024 total pixels) but specify via CSS that it should appear as width:800px; height:16px. The same thing applies to HTML Canvas:
The width and height attributes of the canvas element itself decide how many pixels you can draw on. If you don't specify the height and width of the canvas element, then per the specs:
"the width attribute defaults to 300, and the height attribute defaults to 150."
The width and height CSS properties control the size that the element displays on screen. If the CSS dimensions are not set, the intrinsic size of the element is used for layout.
If you specify in CSS a different size than the actual dimensions of the canvas it must be stretched and squashed by the browser as necessary for display. You can see an example of this here: http://jsfiddle.net/9bheb/5/
The explanation is here: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#attr-canvas-width as seen in another post, thanks!
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.
The best way to size your canvas is to include in a div and style your div with the size that you want.
Here is the CSS
<style>
#divCanvas{
width: 800px;
height: 600px;
}
</style>
Here is the HTML
<div id="divCanvas">
<canvas id="canvas"></canvas>
</div>

How does Pinterest keep their image height proportionate

I want to load in a bunch of random images (of varying widths and heights) to a column. The column will have a fixed width, and the height will have to be cropped off proportionally to keep the image in it's original height to width ratio. (similar to how Pinterest structures their boards.)
Anyone know how this could be accomplished with Javascript or JQuery?
You can just use css:
img.autosize {
width: 500px; /*Specify your width here*/
height: auto;
}
This will keep the images in your site to a fixed width (use max-width in case you don't want all of them to be the exact same width) and the height will adjust itself accordingly to maintain aspect ratio.
Of course, if you want to use javascript or jQuery, you can set the css properties in your script. This is just a hassle-free way to do it.

Background Image Scaling While Maintaining Aspect Ratio

I would like to have images for my background that change automatically like a slide show. But I would like the images to fill the background no matter what size the browser window is...and if it is scaled down, the aspect ratio of the image does not change.
Here is an example of what I'm trying to do:
http://www.thesixtyone.com/
How can I accomplish these tasks? Any help will be much appreciated.
With CSS3, you would use background-size property.
background-size: contain;
Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.
Contain always fits the entire image within your viewport, leaving opaque borders on either the top-bottom or the left-right whenever the ratio of the background image and browser window are not the same.
background-size: cover;
Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.
Cover always fills the browser window, cutting off some hair or ears in the process, which is what I personally prefer for most cases. You can control how your image is aligned within the viewport by using the background-position property.
You can't, at least not like you are trying to now.
What you can do, however, is create an <img> instead, and with css set position:absolute, scale it to 100% width and crop it from the parent with overflow:hidden
example: http://jsfiddle.net/GHmz7/4/
You could try jquery/js to change the background image:
<!doctype html>
<html>
<head>
<title>Width resolution</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
font-size: 20px;
font-family: arial,helvetica,sans-serif;
font-weight: 700;
color:#eee;
text-shadow: 0px 0px 1px #999;
}
div {
width:auto;
height:340px;
border:#ccc groove 2px;
padding:5px;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('body').css({'background-color':'#ccc'});
var sw = screen.width;
function wres() {
switch(sw) {
case 1920:
$('div').css({'background':'#192000 url(bg-1920.jpg)'});
$('body').css({'background':'#001920 url(bg-1920.jpg)'});
break;
case 1600:
$('div').css({'background':'#160000 url(bg-1600.jpg)'});
$('body').css({'background':'#001600 url(bg-1600.jpg)'});
break;
case 1280:
$('div').css({'background':'#128000 url(bg-1280.jpg)'});
$('body').css({'background':'#001280 url(bg-1280.jpg)'});
break;
case 1152:
$('div').css({'background':'#115200 url(bg-1152.jpg)'});
$('body').css({'background':'#001152 url(bg-1152.jpg)'});
break;
default:
$('div').css({'background':'#102400 url(bg-1024.jpg)'});
$('body').css({'background':'#001024 url(bg-1024.jpg)'});
}
//alert(rsw);
//$('div').html(rsw);
$('.res').append(' '+sw);
$('div.res').css('width', 1920);
}
//alert(sw);
wres();
});
</script>
</head>
<body>
<h1 class="res">Resolução atual:</h1>
<div class="res">The div</div>
</body>
</html>
You can create CSS classes for the backgrounds instead, and use .toggleClass()
You can not reliably resize background images across all browsers/versions etc...
The effect you see on thesixtyone.com site is achieved by stretching a normal inline image to 100% of it's container which is a placeholder division. Other elements are then floated over the top of this 'background' division.
So the answer is not to use a background image, but to make an image fill the screen in a placeholder, then put other elements on top of it.

Categories

Resources