HTML5 - Detecting image size, resizing canvas - html

I recently made and hosted Catifier.com.
It's working pretty good, except I have a bug with saving I have to work out, and it stretches images when you set them as the background.
Portrait images look horrible.
Would it be possible to detect the width and height of the image a user pastes in the box, then resize the canvas accordingly?

You have to load your picture in a DOM element to know its size.
So basicly when you want to do it, here are the steps :
Add your picture in an invisible DOM element.
You will be able to get picture width and heignt when onload event is lauched.
Then create your canvas depending those two variables.
All can be done in very few javascript lines.

Just gonna write up a very generic and likely not fully functional way to do this real quick just to give more of an idea.
var img = document.getElementByTagName('img');
for (var i = 0; i < img.length; i++) {
var width = img[i].width,
height = img[i].height;
// do some stuff with the img[i] width and height here if you like. for each image on the page...
}
Not how you'd end up actually doing it but it's just as simple as doing, img.width or height. If that helps more at all.

Related

HTML canvas best practices for resizing

Doing a simple 2d physics engine with HTML5 Canvas (collisions,graphing). I want a full screen canvas with a header navbar. How can I create this layout and handle resizing correctly?
I have tried several solutions:
One involved programatically resizing the canvas to fill its container onload() and onresize(). Canvas contents stay the same.
Another involved a responsive canvas with percents whose contents shrunk as the canvas shrunk.
Can anyone help lead us to the holy grail? The most important question is your opinion about canvas resizing best practices (should we do it?). If so, what about the debate between resizing the canvas pixels and media queries vs flex/percents vs javascript container measuring, etc.
Example/Attempts:
Example-1:
Here is the Javascript code which I used in v1 of my mock up. The corresponding HTML was just a basic document with a header and a 100% container with the canvas inside the container and being set to fill the container.
window.onload = function(){
init();
};
window.addEventListener("resize", init);
function init(){
console.log("init");
initCanvas();
drawCircle();
}
function initCanvas() {
var content = document.querySelector(".content");
var canvas = document.querySelector(".myCanvas");
canvas.width = content.clientWidth;
canvas.height = content.clientHeight;
}
Example-2:
This CodePen is an example of the resizing canvas that I made. It still retreats up under the navbar during extreme resizing though.
Resizing
It will depend on how you are rendering.
requestAnimationFrame is best practice.
Generally best practice to make any changes to the DOM is to use requestAnimationFrame to ensure that changes are presented in sync with the display hardware's refresh. requestAnimationFrame also ensure that only when the page is visible will the changes be made. ie (if the client switches tabs to another tab, your tab will not fire any requestAnimationFrame events)
It is also best to keep the canvas resolution as low as possible. Keeping the canvas at a resolution higher than the display means you will be doing a lot of needless rendering on portions that are off screen, or if you are scaling the canvas via CSS the down or upsampling can result in a variety of unwanted artifacts.
The problem with the resize event.
The resize event is triggered by a variety of sources, OS events that change the window size, mouse events, or from Javascript. None of these events are synced to the display, and some resize events can fire at very high rates (mouse driven resize can fire 100+ times a second)
Because resizing the canvas also clears the image data and resets the context state, each resize requires a re-rendering of the content. The rapid firing rate of the resize event can overwork the thread and you will start to lose events , the page will feel laggy and you can get parts of the page that are not updated in time for the next display frame.
When resizing you should try to avoid resizing when not needed. Thus the best time to resize is via a requestAnimationFrame callback.
Realtime rendering
If you are rendering in realtime then the best way to resize is to compare the canvas size to the container's or window size at the start of every render frame. If the sizes do not match then resize the canvas.
// no need for a resize event listener.
function renderLoop(){
// innerWidth / height or containor size
if(canvas.width !== innerWidth || canvas.height !== innerHeight){
canvas.width = innerWidth;
canvas.height = innerHeight;
}
// your code
requestAnimationFrame(renderLoop);
}
requestAnimationFrame(renderLoop);
Static renders
If you are rendering infrequently or as needed. Then you may be best off to keep a canvas at a standard resolution offscreen and use a resizable canvas on screen to render a view of the offscreen canvas.
In that case you keep a main loop alive that will check a semaphore that indicates that there is a need to update the view. Anything that changes the canvas will then just set the flag to true.
const mainCanvas = document.createElement("canvas");
const mCtx ...
const canvas = document.getElementById("displayCanvas");
const ctx ...
// when updating content
function renderContent(){
mCtx.drawStuff...
...
updateView = true; // flag the change
}
// the resize event only need flag that there is a change
window.addEventListener("resize",()=> updateView = true );
var updateView = true;
function renderLoop(){
if(updateView){
updateView = false; // clear the flag
// is there a need to change display canvas resolution.
if(canvas.width !== innerWidth || canvas.height !== innerHeight){
canvas.width = innerWidth;
canvas.height = innerHeight;
}
// draw the mainCanvas onto the display canvas.
ctx.drawImage(mainCanvas, viewOrigin.x, viewOrigin.y);
}
requestAnimationFrame(renderLoop);
}
requestAnimationFrame(renderLoop);
In your case using the above method (even for realtime) gives you better control over what part of the canvas content is seen.
CSS
Some poeple consider that CSS is the only place any type of visual content should be changed. The problem with the canvas is that CSS can not set the canvas resolution so if you use CSS you still have to set the canvas resolution.
For the canvas I do not set any CSS sizes and let the canvas resolution properties set the display size canvas.width=1920; canvas.height=1080; I can not see the point of having having to set the CSS width and height when there is no need to
Note: If you do not use requestAnimationFrame you will need to set the CSS size as you can not guarantee the canvas resolution will be set in time for the next refresh, while auto CSS updates (eg canvas.style.width="100%") will change in sync with the display device.
It works, you could check it with element inspect.
And I was thinking you wanted change the style width/height of canvas, not the width or height of canvas, they are quite different.
The width or height of canvas would just affect the ratio of things you draw on the canvas. And the CSS style width or height could change the display size of the canvas.

How do I refresh CSS after javascript runs to adjust div height

I'm using the following script to adjust the height of a container div on my page relative to the browser window's height
function thirty_pc() {
var height = $(window).height();
var thirtypc = (50 * height) / 100;
thirtypc = parseInt(thirtypc) + 'px';
var thirtypc2 = thirtypc * 2;
$("#slider").css('height',thirtypc);
}
$(document).ready(function() {
thirty_pc();
$(window).bind('resize', thirty_pc);
});
The script works fine to scale the #slider div's height relative to the viewport's height. The problem is if I resize the browser window the inside div elements dimensions get distorted. However if I refresh the browser the inside div elements fix themselves. Also if I go into firebug while the inside div's are distorted and I un-check ANY even unrelated elements CSS properties, the inside div's fix themselves.
Would the solution be for javascript to somehow refresh CSS after a browser re-size? If so how do you do that? Or should I be tying in the effected inside div element's dimensions to the function to begin with? I have also tried to do that with no luck.
The fact that a browser or CSS refresh seems to fix the problem makes me lean towards the first solution if it's possible.
Thanks.
First off, I suggest you make a text space... a simplified version to learn with. Here is a jsFiddle as an example how you can make an example that doesn't have all the other site stuff in the way. CSS is read once. the js is writing inline CSS. So you don't want to refresh the CSS. You want to write new inline CSS over the stuff the js already wrote.
Here is an example of a function. Below is how you call it on DOM ready and then, also when the window is resized. Keep in mind that it is going to run that function many many many times while you resize - so this isn't great for all scenarios. Also, - while it's commendable that you want it to resize(I do the same) no one else is going to resize their browser... So pick your battles.
var your_functions_name = function() {
var windowHeight = $(window).height();
$('.box').css('height', windowHeight/2);
};
// run on document ready
$(document).ready(your_functions_name);
// run on window resize
$(window).resize(your_functions_name);

Fixed Position Width

Well I am working on an small website.
However I have problem with fixed position.
My header is 770px in width. It contain a couple of elements with it.
position: fixed; works really fine, but when I resize my website to another screen size, something like 640x480 the fixed element (header) cannot be fully visible in width.
I want it to be fixed for scrolling but I want it to be fully visible in width, if user is on smaller screen and cannot see it completely.
Here is an example on an wordpress theme.
http://dvl-den.net/
Same problem is with my small project. Try to open that website on 640x480 (resize browser) and you'll see my problem.
Thanks in advance.
I don't think there is a solution with CSS only properties. I'd try having position: absolute; on my CSS, and playing around JavaScript (my example requires jQuery) like:
jQuery(function($) { // document ready
var $win = $(window),
handler = function() {
// try not to overload browser, creating a throttle
var throttle,
throttleFn = function() {
// this is what happens on window resize
$('#header').css({
top: $win.scrollTop()
});
};
return function() {
clearTimeout(throttle);
throttle = setTimeout(throttleFn, 100);
};
};
$win.resize(handler());
});
It doesn't work really "cool" in mobile, but it's widely know there are mobile issues with fixed headers in web apps (different than native). If you need I can update with a JSFiddle example.
Check demo at: http://jsfiddle.net/qaKT7/ (you can play around with that 100 value to get a better experience, and also use .animate() instead of .css() to make it look fancier)
Try giving
min-width:770px;
or try with media queries
I think there're two ways:
Changing the width "770px" to a percentage.
Detecting the pixel height of screen, then adjusting the width according to this.

Scaling canvas element with static resolution

I have canvas element and I want to scale it down, but without changing it's js logic. Drawing space in js should always be 600x300px, even if it is displayed in HTML as 300x150px. I know, I can resize image with static resolution, but can I do the same with canvas?
Changing the size using CSS scales it
Live Demo
So basically you set its size for drawing objects, etc, via the width and height properties like so
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 300;
and then change its displayed size using css
#canvas{
width: 300px;
height: 150px;
}​
Loktar has one way, using CSS, but that might cause some things to look funny. For instance paths scaled using CSS and scaled using the canvas' own transform may look very different (with the CSS ones looking bad and the canvas ones looking smooth). This depends on the browser though and might be perfectly fine. On chrome at least, text scaled this way looks very bad.
Instead I'd recommend looking at what I wrote here about the concept of "model" coordinates: Working with canvas in different screen sizes
Write everything as if the drawing space is 600x300, but keep a canvas that is 300x150.
Before drawing anything use ctx.scale(0.5, 0.5); and everything will look great!
It's quite possible after all to write one canvas app and the have it scale to all sorts of screens, even if you're just targeting one screen size.

html5 canvas scaling without specifying dimensions

I've just started working with the html5 canvas element.
I'm using the latest firefox and chromium browsers. And so far, they're
responding alike.
What I'm trying to achieve is scaling of an image without having to
specify the canvas or image drawing sizes. I'd like the canvas to fill
the browser window, and for the image to fill the canvas without
specifying any sizes. And to readjust canvas and its image on the
fly when the user adjusts the browser's frame.
The mansion pic that I'm testing with is 4284x2844.
I've managed to achieve dynamic scaling, but there's a problem...
if I don't specify sizes the image becomes blurry.
This is my first stackoverflow question and I haven't conquered the
formatting. So, please take a look at the small amount of code over
at pastebin:
http://pastebin.com/88faqJUx
Thank you for your help.
I found the solution...
Adding two lines, with no other changes, did the trick, though at this point I'm not exactly sure
why it was originally failing, but thoroughly happy to move on...
<canvas id="taba_main_canvas">
Your browser does not support the canvas element.
</ canvas>
<script type="text/javascript">
var main_canvas=document.getElementById("taba_main_canvas");
var cxt=main_canvas.getContext("2d");
// adding these next two lines solved the blurriness issues
//Set the canvas width to the same as the browser
main_canvas.width = window.innerWidth;
main_canvas.height = window.innerHeight;
var img=new Image();
<!-- mansion pic 4284x2844 -->
img.src="images/mansion_3344.png";
img.onload = function()
{
<!-- use the graphics full size and scale the canvas in css -->
cxt.drawImage(img,0,0,main_canvas.width,main_canvas.height);
}
</script>
Just one tiny little problem, the vertical size of the image is apparently just a few lines taller
than the canvas and so I get a vertival scrollbar. Dragging the browser window taller, which normally
would eliminate the vertical scrollbar has no effect. I've tried manipulating the canvas or image height
in the code, but that didn't change anything.
Still, having the image look clean is a big win. I'm moving on for the moment and will revisit this
later.
The other way to do this is to latch on to the document onresize event and resize the canvas by using window.innerWidth and window.innerHeight or some such thing. I've used it that way myself, but that was for something which I didn't care about IE support - see W3C DOM Compatibility - CSS Object Model View at quirksmode for info about browser support. Note also that the scrollbar width is included in innerWidth and innerHeight; if your page may need scrolling, you may wish to do something like subtract 20 and pad the containing element with a suitable background colour.
I presume that you're not just trying to draw an image - if you were just doing that, <img> would be a much better match.
Edit: jQuery has $(document).width(); and $(document).height(); which seem to get the right figures. Another edit: actually they're wrong; they're the document width and height, not viewport width and height, so I think innerWidth and innerHeight may be all there is.