Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make background image shrink proportionally to fit button size in javascript?

I am making a chessboard in javascript. The chessboard's squares (buttons) were originally designed to be 60px by 60px, but now they are 40px by 40px.

    button      {       width:40px;        height:40px;        border: 0     } 

However, some of the pieces that were designed for this earlier chessboard are still 60px by 60px. Is there any way in Javascript to make the images shrink proportionally to fit the square size? Currently, the images fit the square size, but do not shrink, so when I say,

    square.style.backgroundImage = imgLink; // square is the button, imgLink is "WhiteKing.jpg" for example. 

I get pieces like this -

enter image description here

If the WhiteKing.jpg had shrunk proportionally, it would have fit nicely. Is there a way to do this in Javascript? Any help would be really appreciated.

like image 263
CodeBlue Avatar asked Feb 29 '12 22:02

CodeBlue


People also ask

How do I stretch a background image to fit?

When you work with background images, you may want an image to stretch to fit the page despite the wide range of devices and screen sizes. The best way to stretch an image to fit the background of an element is to use the CSS3 property, for background-size, and set it equal to cover.

How do I make the background image fit my screen size in HTML?

Try this , background: url(../IMAGES/background. jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; For more information , follow this Perfect Full Page Background Image !!

How do you make a background image fit your screen in CSS?

Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.


2 Answers

Most modern browsers have support for CSS background-image options like background-size, so you may really use something like this:

button{   width:40px;    height:40px;    border: 0;   background-size: 100%; /* To fill the dimensions of container (button), or */   background-size: 40px auto; /* to specify dimensions explicitly */ } 

Of course you can use that in JavaScript too (but it's better to add it to already existing CSS for button):

square.style.backgroundSize = '100%'; 
like image 85
Juicy Scripter Avatar answered Sep 22 '22 17:09

Juicy Scripter


Your going to want to use: Background-size: 100%;

like image 37
Ken Wheeler Avatar answered Sep 21 '22 17:09

Ken Wheeler