JavaScript linear gradient Three _javascript techniques

Source: Internet
Author: User
Tags cos sin hasownproperty
IE there is still a sharp weapon has not been used, that is VML. Although not as SVG, it is still very powerful. On the implementation gradient, its fill is much more powerful than IE's gragient filter. But VML appeared earlier, supporting only a few color names, such as Red,blue,yellow, and others like Orange could kill it. So to use VML to do linear gradients, we have to do a conversion of these color names.
Color value of HTML4
Black = #000000 Green = #008000 Silver = #c0c0c0 Lime = #00ff00
Gray = #808080 Olive = #808000 White = #ffffff Yellow = #ffff00
Maroon = #800000 Navy = #000080 Red = #ff0000 Blue = #0000ff
Purple = #800080 Teal = #008080 Fuchsia = #ff00ff Aqua = #00ffff
We can learn more about color values on the website of Firefox and the consortium.
Copy Code code as follows:

var htmlcolor={black: "#000", Green: "#008000", Silver: "#c0c0c0", Lime: "#0f0",
Gray: "#808080", Olive: "#808000", White: "#fff", Yellow: "#ff0",
Maroon: "#800000", Navy: "#000080", Red: "#f00", Blue: "#00f",
Purple: "#800080", Teal: "#008080", Fuchsia: "#f0f", Aqua: "#0ff",
Indigo: "#4b0082", Orange: "#ffa500", Sienna: "#a0522d", Plum: "#dda0dd",
Gold: "#ffd700", Tan: "#d2b48c", Snow: "#fffafa", Violet: "#ee82ee"
}

We then create a RECT element of the same size inside the element that requires a linear gradient, and then add a fill element inside it to set the gradient. Pseudo code is as follows:
Copy Code code as follows:

<div class= "Gradient" style= "Position:relative;width:width;height:height" >
JavaScript linear gradient by Shizhong us to achieve multiple horizontal gradient effects
<vml:rect style= "position:absolute;width:width;height;top:0;left:0" stroked= "F" >
<vml:fill colors= "Color-stop" focus= "100%" type= "gradient" method= "linear"/> ", corresponding to SVG"
</vml:rect>
</div>

<!doctype html> <title>javascript linear gradient by Masaki </title> <meta charset= "Utf-8"/> <meta name= " Keywords "content=" javascript linear gradient by Masaki "/> <meta name=" description "content=" JavaScript linear gradient by Masaki "/> < Style type= "Text/css" > gradient{width:800px; height:100px; } </style> <script type= "Text/javascript" > var gradient = function (id) {var entity = Document.getelementby ID (ID), options = Arguments[1] | | {}, Width = options.width, height = options.height, type = options.type, stops = options["Color-stop"]; This.init (Entity,stops,width,height,type); } gradient.prototype ={constructor:gradient, Init:function (entity,stops,width,height,type) {this.css (entity,{posit Ion: "Relative"}); var content = entity.innerhtml; entity.innerhtml = ""; !+ "\v1"? This. Iegradient (Entity,stops,width,height,type): this. Svggradient (entity,stops,width,height,type) var contentdiv = document.createelement ("div"); This.css (contentdiv,{Position: "Absolute", top:0,left:0}) contentdiv.innerhtml = content; Entity.appendchild (CONTENTDIV); }, Css:function (node,bag) {var str = ";" for (var i in bag) {if (Bag.hasownproperty (i)) str + = i = = "opacity"? ("Filter:alpha (opacity=" + bag[i] * 100+ "):( i+ ":" +bag[i]+ ")} Node.style.cssText = str; }, Attr:function (Node,bag) {for (var i in bag) {if (Bag.hasownproperty (i)) Node.setattribute (I,bag[i])}}, CREATESV G:function (tag) {return Document.createelementns ("Http://www.w3.org/2000/svg", tag); }, Iegradient:function (Entity,stops,width,height,type) {if (!DOCUMENT.NAMESPACES.VML) {Document.namespaces.add (' VML ', ' urn:schemas-microsoft-com:vml '); var vmlobj = document.createelement ("<object classid=clsid:10072cec-8cc1-11d1-986e-00a0c955b42e id=VMLRender> "), head = document.getElementsByTagName (" head ") [0]; Head.appendchild (Vmlobj) Document.createstylesheet (). addrule (". VML", "Behavior:url (#VMLRender); Display:inline-block; ");} var rect = Document.createeLement (' <vml:rect class= ' vml ">"); Entity.appendchild (rect); This.css (rect,{width:width+ "px", height:height+ "px"}); This.attr (rect,{stroked: "F"}); var fill = document.createelement (' <vml:fill class= "VML" > "); var colors = ""; for (Var i=0,l=stops.length;i<l;i++) {var offset = Stops[i].split (",") [0] + "%", color = This.hex (Stops[i].split (",") [ 1]); Colors + = offset + "" +color + ","; } rect.appendchild (fill); var angle = type? 90:0; This.attr (fill,{type: "Gradient", Colors:colors,method: "Sigma", Focus: "100%", Angle:angle}); }, Svggradient:function (Entity,stops,width,height,type) {var svg = this.createsvg ("SVG"), id = "id" + (new Date (). Getti Me () * Math.random ()). toFixed (0); This.attr (svg,{width:width+ "px", height:height+ "px"}) entity.appendchild (SVG); var defs = this.createsvg ("defs"); Svg.appendchild (defs); var lineargradient = this.createsvg ("LinearGradient"); Defs.appendchild (lineargradient); This.attr (lineargradient,{id:id,x1: "0%", y1: "0%"}) if (type) {thIs.attr (lineargradient,{x2: "100%", y2: "0%"})}else{this.attr (lineargradient,{x2: "0%", y2: "100%"})} for (Var i=0,l= stops.length;i<l;i++) {var offset = Stops[i].split (",") [0] + "%", color = This.hex (Stops[i].split (",") [1]), stop = t His.createsvg ("Stop"); This.attr (Stop,{offset:offset, "Stop-color": color}); Lineargradient.appendchild (stop); var rect = this.createsvg ("rect"); Svg.appendchild (rect); This.attr (rect,{x: "0px", Y: "0px", width:width+ "px", height:height+ "px", fill: "URL (#" +lineargradient.getattribute (" ID ") +") "}); Hex:function (value) {var color={black: "#000", Green: "#008000", Silver: "#c0c0c0", Lime: "#0f0", Gray: "#808080", Oliv E: "#808000", White: "#fff", Yellow: "#ff0", Maroon: "#800000", Navy: "#000080", Red: "#f00", Blue: "#00f", Purple: "#800080" , Teal: "#008080", Fuchsia: "#f0f", Aqua: "#0ff", Indigo: "#4b0082", Orange: "#ffa500", Sienna: "#a0522d", Plum: "#dda0dd", g Old: "#ffd700", Tan: "#d2b48c", Snow: "#fffafa", Violet: "#ee82ee"} if (!! Color[value]) {value = Color[value]} if (/^#/.test (value)) {value = Value.replace (' # ', '); Return "#" + (Value.length = 3 Value.replace (/^ (\w) (\w) (\w) $/, ' $1$1$2$2$3$3 '): value); return value; } window.onload = function () {New gradient ("Text1", {width:800,height:100,type:1, "color-stop": ["0,red", "16,orange", "32,yellow", "48,green", "64,blue", "80,indigo", "100,violet"]}) New gradient ("Text2", {width:800,height:100,type:0, " Color-stop ": [0,red", "16,orange", "32,yellow", "48,green", "64,blue", "80,indigo", "100,violet"]} </script> <div id= "Text1" class= "gradient" >javascript linear gradient by Shizhong the United States to achieve multiple horizontal gradient effect </div> <div id= "Text2" class= "Gradien" T ">javascript linear gradient by Shizhong us to achieve multiple vertical gradient effects </div>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Using VML to achieve the linear gradient of IE, the length of the entire class is reduced by half.
Let's see how to achieve the angle gradient, ie side good, directly into a corner on the line (0-360, can also be negative). SVG is troublesome, it by the LinearGradient four attributes to control the gradient, x1,x2,y2,y2, the essence is two points. Suppose the first point is (0,0), the second point is (100,0), and it is a horizontal gradient. Suppose the first point is (0,0), the second point is (0,100), and it is a vertical gradient. To skew, you must make the coordinates of the second point completely unequal to the coordinates of the first point, whether it is an x or a Y axis. This is going to use trigonometric functions.
Copy Code code as follows:

var x = (Math.sin (angle*math.pi/180) *). ToFixed (2) + "%";
var y = (Math.Cos (angle*math.pi/180) *). ToFixed (2) + "%";
This.attr (Lineargradient,{x2:x,y2:y});

We should also see that the horizontal and vertical gradients are just a special case, we can abolish the attribute of type, change it to angle, and pass in a number from 0 to 360.
<!doctype html> <title>javascript linear gradient by Masaki </title> <meta charset= "Utf-8"/> <meta name= " Keywords "content=" javascript linear gradient by Masaki "/> <meta name=" description "content=" JavaScript linear gradient by Masaki "/> < Style type= "Text/css" > gradient{width:800px; height:100px; } </style> <script type= "Text/javascript" > var gradient = function (id) {var entity = Document.getelementby ID (ID), options = Arguments[1] | | {}, Width = options.width, height = options.height, angle = options.angle, stops = options["Color-stop"]; This.init (Entity,stops,width,height,angle); } gradient.prototype ={constructor:gradient, Init:function (entity,stops,width,height,angle) {this.css (Entity,{posi tion: "Relative"}); var content = entity.innerhtml; entity.innerhtml = ""; !+ "\v1"? This. Iegradient (Entity,stops,width,height,angle): this. Svggradient (entity,stops,width,height,angle) var contentdiv = document.createelement ("div"); This.css (ContenTdiv,{position: "Absolute", top:0,left:0}) contentdiv.innerhtml = content; Entity.appendchild (CONTENTDIV); }, Css:function (node,bag) {var str = ";" for (var i in bag) {if (Bag.hasownproperty (i)) str + = i = = "opacity"? ("Filter:alpha (opacity=" + bag[i] * 100+ "):( i+ ":" +bag[i]+ ")} Node.style.cssText = str; }, Attr:function (Node,bag) {for (var i in bag) {if (Bag.hasownproperty (i)) Node.setattribute (I,bag[i])}}, CREATESV G:function (tag) {return Document.createelementns ("Http://www.w3.org/2000/svg", tag); }, Iegradient:function (Entity,stops,width,height,angle) {if (!DOCUMENT.NAMESPACES.VML) {Document.namespaces.add (' VML ', ' urn:schemas-microsoft-com:vml '); var vmlobj = document.createelement ("<object classid=clsid:10072cec-8cc1-11d1-986e-00a0c955b42e id=VMLRender> "), head = document.getElementsByTagName (" head ") [0]; Head.appendchild (Vmlobj) Document.createstylesheet (). addrule (". VML", "Behavior:url (#VMLRender); Display:inline-block; ");} var rect = document.CreateElement (' <vml:rect class= ' vml ">"); Entity.appendchild (rect); This.css (rect,{width:width+ "px", height:height+ "px"}); This.attr (rect,{stroked: "F"}); var fill = document.createelement (' <vml:fill class= "VML" > "); var colors = ""; for (Var i=0,l=stops.length;i<l;i++) {var offset = Stops[i].split (",") [0] + "%", color = This.hex (Stops[i].split (",") [ 1]); Colors + = offset + "" +color + ","; } rect.appendchild (fill); This.attr (fill,{type: "Gradient", Colors:colors,method: "Sigma", Focus: "100%", Angle:angle}); }, Svggradient:function (Entity,stops,width,height,angle) {var svg = this.createsvg ("SVG"), id = "id" + (new Date (). Gett IME () * Math.random ()). toFixed (0); This.attr (svg,{width:width+ "px", height:height+ "px"}) entity.appendchild (SVG); var defs = this.createsvg ("defs"); Svg.appendchild (defs); var lineargradient = this.createsvg ("LinearGradient"); Defs.appendchild (lineargradient); This.attr (lineargradient,{id:id,x1: "0%", y1: "0%"}) var x = (Math.sin (angle*math.pi/1*). toFixed (2) + "%"; var y = (Math.Cos (angle*math.pi/180) *). ToFixed (2) + "%"; This.attr (Lineargradient,{x2:x,y2:y}); for (Var i=0,l=stops.length;i<l;i++) {var offset = Stops[i].split (",") [0] + "%", color = This.hex (Stops[i].split (",") [ 1]), stop = This.createsvg ("Stop"); This.attr (Stop,{offset:offset, "Stop-color": color}); Lineargradient.appendchild (stop); var rect = this.createsvg ("rect"); Svg.appendchild (rect); This.attr (rect,{x: "0px", Y: "0px", width:width+ "px", height:height+ "px", fill: "URL (#" +lineargradient.getattribute (" ID ") +") "}); Hex:function (value) {var color={black: "#000", Green: "#008000", Silver: "#c0c0c0", Lime: "#0f0", Gray: "#808080", Oliv E: "#808000", White: "#fff", Yellow: "#ff0", Maroon: "#800000", Navy: "#000080", Red: "#f00", Blue: "#00f", Purple: "#800080" , Teal: "#008080", Fuchsia: "#f0f", Aqua: "#0ff", Indigo: "#4b0082", Orange: "#ffa500", Sienna: "#a0522d", Plum: "#dda0dd", g Old: "#ffd700", Tan: "#d2b48c", Snow: "#fffafa", Violet: "#ee82ee"} IF (!!!) Color[value] {value = Color[value]} if (/^#/.test (value)) {value = Value.replace (' # ', '); Return "#" + (Value.length = 3 Value.replace (/^ (\w) (\w) (\w) $/, ' $1$1$2$2$3$3 '): value); return value; } window.onload = function () {New gradient ("Text1", {width:800,height:100,angle:90, "color-stop": ["0,red", "16,orange "," 32,yellow "," 48,green "," 64,blue "," 80,indigo "," 100,violet "]}) New gradient (" Text2 ", {Width:800,height:100,angle : 0, "color-stop": ["0,red", "16,orange", "32,yellow", "48,green", "64,blue", "80,indigo", "100,violet"]}) New Gradient (" Text3 ", {width:800,height:100,angle:45," color-stop ": [" 0,red "," 16,orange "," 32,yellow "," 48,green "," 64,blue "," 80, Indigo "," 100,violet "]})} </script> <div id=" Text1 "class=" gradient ">javascript linear gradient by Shizhong to achieve multiple horizontal gradient effect < /div> <div id= "Text2" class= "gradient" >javascript linear gradient by Shizhong us to achieve multiple vertical gradients </div> <div id= "Text3" C lass= "gradient" >javascript linear gradient by Shizhong beauty to achieve multiple-angle gradient effect </div>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.