so i have a canvas element just doing some background animations for an app.
my question is, whats the best way to make sure it looks the same on different devices?
am i best making different size canvas elements and using CSS media quires?
or is there a way to make the canvas flexible and responsive to fill 100% of the viewport using JS or html?
any help would be great!
<html>
<head>
<meta charset="utf-8" />
<title>Canvas Resize</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
You need to explicitly set the width and height of the canvas. Don't use CSS to set canvas size as this affects only the element but not its bitmap (your canvas bitmap/image will be stretched).
Here is one way:
/// assuming canvas variable exists in global scope
window.addEventListener('resize', resizeCanvas, false);
resizeCanvas(); /// call the first time page is loaded
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
You can then add CSS rules to the canvas element:
#myCanvas {
position:fixed; /* or absolute (or not..) depending on your goal */
left:0;
top:0;
}
Your document html and body must also be setup properly with CSS:
html, body {
width:100%;
height:100%;
margin:0;
}
If you want to cover the whole window also add overflow: hidden to the last CSS rule to avoid any scroll-bars.
Hope this helps.
Use the CSS 100% variable.
canvas {
width: 100%;
height: 100%;
border: solid black 1px;
}
<canvas id="canvas"></canvas>
Related
I have a little issue positioning an element outside the canvas to star an animation from the outside. An example bellow.
.square {
height: 50px;
width: 50px;
background-color: #555;
position: absolute;
right: -10px;
}
<html>
<head>
</head>
<body>
<div class="square"></div>
</body>
</html>
This is a reference image about the expected start position of the element (red dotted box).
Anyone know how to configure the css related to the object to position it outside the canvas without increases their (canvas) size?
Hopefully without deactivate the scroll bar (for example to increase the left side of the canvas) and not over the canvas (to keeping it scrollable and not relative)
I thought this is the simplest question ever, but i couldn't find on the web, hope to be helpful to someone, thanks!
I am trying to create a web based paint software, and want to position a button to change the color of the paint brush (I will eventually change this to a bar). How would I position the button on the right of the canvas.
Html and css:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Paint</title>
<style>
#canvas{
background-color: cadetblue;
}
.button{
/* code to position button next to canvas */
}
</style>
</head>
<body>
<canvas id = "canvas" width = "800" height = "600"></canvas>
<div class = "button">RED</div>
</body>
</html>
<canvas> is just a normal block element, so you can position it however you will position a block element. You can apply float:left on the canvas & the button (please use a real <button>), you can display:inline-block them, you can add a wrapper around them and display: flex it, or even display: grid it or add position: relative to it and position: absolute to its children. There are lots of ways to achieve this. Here is a good starting point: https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Introduction
Is it possible to make a <div> adapt to its background image? I mean to maintain the proportions width and height.
Clarification:
The div change the width. (it is a responsive design)
I do not mean to make the background adapt to the div. This is possible with background-size. But what I am asking is the way round: to have a image in the background and make the div parent adapt to that image whatever its size is.
I know that I can do something similar if I put the image in the html, and not in the background. But in this case, I could not change the image for different device sizes. So I am asking to put the image in background to be able to change it with CSS.
In the example I give, I can make the image adapt to the width but I get a gap with the height. Can I make the div adapt to the height too of the image , as the image changes its size? Asked in another way: In a responsive environment, can a div with an image background, change in size without leaving empty spaces ?
Here is the example to play.
CSS:
#image {
margin:0px auto;
width:90%;
max-width:512px;
height:512px; /* I need to give heigt to make it visible? */
background-image:url('http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
background-repeat:no-repeat;
background-size:100%;
background-color:yellow;/*just to make visible the gap in the height*/
}
HTML:
<div id="image"></div>
No it is NOT possible to adapt a div to it's background image.
Because it is 'senseless'
This is how:
A div's size is determined by its "content", or if its dimensions are SPECIFICALLY set.
Since the background-image does not fall into any of these categories, you can see that it's impossible.
What you CAN do is this:
HTML
<div class="image-controlled">
<img>...</img>
<div class="content">...</div>
</div>
CSS
.image-controlled {
position: relative;
overflow: hidden <-- optional, if you want to cut off .content which overflows the image boundaries
}
.content {
position: absolute;
top: 0; left: 0; <-- position of the content as it should be (normally)
}
The div will now be the size of the image, and the .content will be shown over it.
Also note that the .content div can come above or below the <img> in order of appearance, but the effect would be the same. But, if you apply a position property on the img element too, then you'll need to set the z-index of .content greater than that of <img>
By using CSS, It's not possible to change an element's dimension according to its background-image size, to achieve this, you should use JavaScript:
HTML:
<div id="image"></div>
JavaScript:
var
img = document.getElementById('image'),
style = img.currentStyle || window.getComputedStyle(img, false),
imgSrc = style.backgroundImage.slice(4, -1),
image = new Image();
image.src = imgSrc;
img.style.width = image.width + 'px';
img.style.height = image.height + 'px';
JSFiddle Demo
Update: jQuery version
Here is the the jQuery version.
var
img = $('#image'),
imgSrc = img.css('background-image').slice(4, -1);
$('<img />')
.attr('src', imgSrc)
.on('load', function() {
img.width(this.width);
img.height(this.height);
});
JSFiddle Demo #2
Yes. We can make background image adapt to its div, like make it responsive too.
Tips for a responsive background image:
background-size:cover-set bg image to background-size cover
-in css the padding set to percentage both top and bottom
-make the bg image no repeat
see this link: https://jsfiddle.net/beljems/dtxLjmdv/
Maybe using javascript, you can get the url to the image:
var img = document.getElementById('image').style.backgroundImage;
var width = img.clientWidth;
var height = img.clientHeight;
document.getElemetById('image').style.width = width;
document.getElemetById('image').style.height = height;
I strongly suspect you cannot do this exclusively with stylesheets.
Ok, my solution is a little bit tricky, but it works. It's a javascript and involve jquery as you wanted. The idea is to create a new image, add it to the DOM, waits till it loads and gets its dimensions. After that the new image is removed and the width and height are applied to the original img tag. Here is a js fiddle demonstrating the workaround http://jsfiddle.net/krasimir/bH5JZ/5/
And here is the code:
$(document).ready(function() {
var image = $("#image");
var imageurl = image.css("background-image").replace(/url/, '').replace(/\(/, '').replace(/\)/, '');
var body = $("body");
var newimage = $('<img src="' + imageurl + '" />');
newimage.css("display", "none");
body.append(newimage);
newimage.on("load", function() {
var w = $(this).width();
var h = $(this).height();
image.css("width", w);
image.css("height", h);
newimage.remove();
});
});
And the css:
#image {
margin: 0px auto;
background-image:url('http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
background-repeat:no-repeat;
background-size:100%;
background-color:yellow;
}
The easiest thing to do that doesn't need any javascript is to set your image as the background image and then make a .gif or a .png of the same size that you set as an overlay image in that div. That transparent .png or .gif will size the div. Transparent .png or .gif are only a couple of KB and your page will complete loading faster than with javascript.
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-image:url("myImage.jpg");
background-size:100% auto;
}
</style>
</head>
<body>
<div><img alt="" src="myOverlay.png"></div>
</body>
</html>
I have a background image on the body of my web page. I have used background-size:cover so that the image stretches across the body whilst maintaining the aspect ratio of the image. I would like this to be the same for IE7 + IE8.
I have looked around and seen the following code:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='AutumnWinter_4.jpg',
sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='AutumnWinter_4.jpg',
sizingMethod='scale')";
But this doesn't preserve the aspect ratio, which is really bad for the website we are aiming at.
Is there any way to do this? Without hitting up jQuery?
What's the reason of not using jQuery? You could load it in conditional comments for IE<8 only, so that for every other modern browser jQuery is not loaded.
Also consider that IE7 has a very low market share (2,52%, April 2012) so it can be acceptable to load ~ 25kb extra for that specific browser if this feature is so important for your site/application.
So, I've found this plugin for jQuery: https://github.com/louisremi/jquery.backgroundSize.js
A jQuery cssHook adding support for "cover" and "contain" to IE6-7-8, in 1.5K
See Github project page for more info.
backgroundSize.js will not actually stretch the bg image in IE7, it seems to just center it at the original size. See their demo and click on 'Check what IE6-7-8 users would normally see.'
#danRhul
I have read that backstretch will work in IE7+
Good luck!
You could just fake a background image with an actual image. It's a bit more HTML editing and certainly not ideal, but since when has handling IE ever been ideal?
<body>
<img id="mainBG" src="mainBG.jpg" />
<div id="content">
[ ... ]
Then style it accordingly
body{
position:relative;
}
#mainBG{
width:100%
position:absolute;
top:0px;
left:0px;
}
Should be cross-browser if I'm not mistaken.
I've used the following (http://css-tricks.com/perfect-full-page-background-image/) and it works well in ie7.
HTML:
<body>
<img class="bg" src="filename">
</body>
CSS:
.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
#media screen and (max-width: 1024px) { /* Specific to this particular image */
img.bg {
left: 50%;
margin-left: -512px; /* 50% */
}
}
I know this is now an old question, but I thought I'd share a solution I came up with for anyone else who finds this question on google, like I did.
I was trying to get an image to cover a site's background and came across this question, however none of the solutions worked for me. I came up with this instead:
HTML: move the background image to an <img />, make it the first thing in your <body>.
<html>
<body>
<img class="background" src="kitty.jpg" />
<div class="content">
...
CSS: make the background appear under the content, set it's min-width/height to 100%.
html {
height: 100%
}
body .background {
position: absolute;
z-index: -1;
min-height: 100%;
min-width: 100%;
}
It's the min-height and min-width here that does the magic. Do not give the image a width and height in the HTML or CSS, or the aspect ratio will change.
The above will work for IE7 and IE8. If you would like to support IE6, you could set a centered image fallback like this:
CSS: If IE6, don't display the image, use a background image instead.
body {
_background: url("kitty.jpg") 50% top no-repeat;
}
body .background {
_display: none;
}
(N.B. If you don't like the underscore hack to target IE6, you could use conditionals instead – that's what the HTML5 Boilerplate does.)
After much trial and error, the best solution was guessing it!
The following worked for me.
body {
background-size:100%;
}
You have two options to achieve this with just CSS:
Use Object-fit: cover. The only problem with this is that it will not work in all browsers
If you want cross browser support, you can follow primitive CSS approach:
Position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Note:
Since transform ONLY works from IE9, you can make use of filters. Here is an answer for this.
Once it is in the centre, you can do,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of Object-fit:cover.
Here is a demonstration of the above logic.
https://jsfiddle.net/furqan_694/s3xLe1gp/
Unfortunately, most solutions to this kind of problem either depend on css3 or ignore the native functionality of "cover" that preserves the original aspect ratio of the image. https://github.com/louisremi/background-size-polyfill is supposed to preserve ratio, but I could never get it to work completely when stretching the browser in certain ways (operator error, I'm sure :-) ). To solve this problem, I wrote a jquery script that I've tested on safari, chrome, ff and ie8+. You'll notice that you will have to use an img positioned absolutely instead of css background-image. Just add the bgImg as an id in the tag in html.
CSS:
.container { height: auto; overflow:hidden; position:relative;}
.container #bgImg { position:absolute; z-index:-1;}
You're image selector will have to be positioned absolutely to get it to sit behind the content. That means that you're parent container has to have position: relative and then overflow: hidden so that whatever overflows from the image (since you're maintaining ratio, some pieces of it inevitable will) is hidden. Be aware also that certain display tags in the parent container will break the hiding of the overflow.
JQUERY:
$(window).load(function () {
// only do this once and pass as function parameters, because chrome
// and safari have trouble not only with document.ready but window.resize
var img = new Image();
img.src = $("#bgImg").attr('src');
var $width_orig = img.width;
var $height_orig = img.height;
resizeBGImage($width_orig, $height_orig);
$(window).resize(function () {
resizeBGImage($width_orig, $height_orig);
});
});
function resizeBGImage($width_img_orig, $height_img_orig) {
// get dimensions of container
var $width_container = $('.container').outerWidth();
var $height_container = $('.container').outerHeight();
// calculate original aspect ratio and ratio of the container
var $imageratio = $width_img_orig / $height_img_orig;
var $containerratio = $width_container / $height_container;
var $wdiff = $width_container - $width_img_orig;
var $hdiff = $height_container - $height_img_orig;
// original size, so just set to original
if (($wdiff == 0) && ($hdiff == 0)) {
$("#bgImg").css('width', $width_img_orig);
$("#bgImg").css('height', $height_img_orig);
}
// if container is smaller along both dimensions than the original image,
// set image to container size
else if (($wdiff < 0) && ($hdiff < 0)) {
$("#bgImg").css('width', $width_img_orig);
$("#bgImg").css('height', $height_img_orig+1); // adding one because chrome can't do math
}
// if container is wider than long relatiave to original image aspect ratio
// set width to container width and calculate height
else if ($containerratio > $imageratio) {
$("#bgImg").css('width', $width_container);
// calculate height using orig aspect ratio and assign to image height
$("#bgImg").css('height', (($width_container * $height_img_orig) / $width_img_orig) + 1); // adding one because chrome can't do math
}
// else container is taller than long relatiave to original image aspect ratio
// set height to container height and calculate width
else {
// set the image height to container height
$("#bgImg").css('height', $height_container + 1); // adding one because chrome can't do math
// calculate width using orig aspect ratio and assign to image width
$("#bgImg").css('width', (($height_container * $width_img_orig) / $height_img_orig));
}
$("#bgImg").css('left', (($width_container - $("#bgImg").width()) / 2).toString() + 'px');
};
Note the use of $(window).load() instead of $(document).ready(). Chrome and safari seem to have issues with the latter since in those browsers, the background image may not be fully loaded when the DOM is. Using $(window).load() ensures all window elements are in place before the script runs.
Sounds like you need a 'shim' or 'polyfill' like Modernizer:
http://modernizr.com/docs/#html5inie
Does anuyone know if it is possible to embed a bing map in fullscreen??
So that the map can always fill the background and simply overlay a few elements on top.
I cannot seem to achieve that with 100% iframe and bing's help is not that helpful.
Thank you
If I understand you correctly, you want to achieve the effect of having the map fill up the entire screen, sort of like using the map as a background, and then have other elements overlaid on top? If so, you should be able to accomplish this easily via the position:fixed CSS Property.
<div id='yourMapDiv' style="position: fixed; top: 0px;
left: 0px; right:0px; bottom:0px; z-index: 100">
</div>
This is saying yourMapDiv will have a fixed position that is 0 pixel away from all four edges of the screen. In effect, you are spanning yourMapDiv across the entire browser screen, without having to specify explicit length or width, and re-sizing will not causing scroll bars to appear:
Here is what going full screen in Chrome looks like:
In the example above I assigned a z-index of 100 to yourMapDiv, to illustrate that if you want other elements to appear above the map, you will have to assign a higher z-index to them.
The answers above did not work for me.
To get a map fill out the browser window without any borders or scrollbars, I had to use the following minimal html file:
<!DOCTYPE html>
<html>
<head>
<title>Bing Map</title>
<meta charset="utf-8" />
<style>
#myMap {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="myMap"></div>
<script type='text/javascript'>
function GetMap() {
new Microsoft.Maps.Map('#myMap', {
credentials: 'your_bing_key'
});
}
</script>
<script type='text/javascript'
src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap' async defer>
</script>
</body>
</html>
You can't "embed a Bing Map in fullscreen", but it's certainly possible to use CSS to set the height and width of the div containing the map to be 100% of the browser, and then maximise (or set to fullscreen) the browser window - is that what you mean?