How to let the page background degrade with JavaScript?

10

It would look something like the image below; I have no idea how to do this.

I do not want to use image, I want to generate with code.

    
asked by anonymous 17.09.2014 / 04:22

2 answers

15
With pure CSS

As an alternative suggestion, a much simpler solution, which does not require the use of JS, with pure and relatively simple CSS:

body {
   background-image: -ms-linear-gradient(top, #FF3300 0%, #EEFF00 100%);
   background-image: -moz-linear-gradient(top, #FF3300 0%, #EEFF00 100%);
   background-image: -o-linear-gradient(top, #FF3300 0%, #EEFF00 100%);
   background-image: -webkit-gradient(linear, top, bottom, color-stop(0, #FF3300), color-stop(1, #EEFF00));
   background-image: -webkit-linear-gradient(top, #FF3300 0%, #EEFF00 100%);
   background-image: linear-gradient(to bottom, #FF3300 0%, #EEFF00 100%);
   /* conforme sugerido pelo @PapaCharlie, seguem soluções pra IE mais velho:
   /*IE7-*/ filter: progid:DXImageTransform.Microsoft.Gradient(
      startColorStr='#FF3300', endColorStr='#EEFF00', GradientType=0);
   /*IE8+*/ -ms-filter: "progid:DXImageTransform.Microsoft.Gradient(
      startColorStr='#FF3300', endColorStr='#EEFF00', GradientType=0)";
}

Result:

Testyour JSFiddle , or use this tool to automatically generate CSS for you.

With JS

I'm not going to repeat the code that is already in the @brasiofilo solution (which has already received my vote too), because I'm basically complementing the idea that it presented, with a way to use the presented gradient solution of the answer as Background image. For this, this method can be used:

Canvas.toDataURL("image/png")

JQuery application example:

$('body').css({'background-image':"url(" + Canvas.toDataURL("image/png")+ ")" });


  

Beware of certain supposedly "JavaScript" solutions over the web. When searching for external alternatives, I noticed that many of them simply generate a CSS, and worse, less than the one posted in the response.

    
17.09.2014 / 04:33
9

The great onetrickpony has an example using the HTML element canvas . According to the documentation, the element is supported by Firefox 1.5+, IE 9+, Chrome and Opera 9. For versions smaller than IE 9, it is necessary to use the Explorer Canvas .

HTML

<canvas id="gradient"></canvas>

CSS

canvas#gradient {
    display: block;
    height: 100%;
    width: 100%;
}

JS

var
  canvas = document.getElementById('gradient'),
  context = canvas.getContext('2d'),
  gradient = context.createLinearGradient(0, 0, 0, canvas.height);

gradient.addColorStop(0, '#ffffaa');
gradient.addColorStop(1, '#770000');  

context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);

JSFiddle

    
17.09.2014 / 04:34