Snap.svg scale and animate SVG - javascript

I'm trying to scale my SVG with g.animate({ transform: "s2.5,2.5," + bbox.cx + "," + bbox.cy }, 0); and then animate wheelAnimation(bbox.cx, bbox.cy, 1500);
var i = 0;
function wheelAnimation(cx, cy, speed){
i++;
g.animate(
{ transform: "r360," + cx + ',' + cy}, // Basic rotation around a point. No frills.
speed, // Nice slow turning rays
function(){
if(i == 5)
speed = 5000;
g.attr({ transform: 'rotate(0 ' + cx + ' ' + cy}); // Reset the position of the rays.
wheelAnimation(cx,cy, speed); // Repeat this animation so it appears infinite.
}
);
}
But my SVG didn't scaling. It's only rotates. If I remove rotation - SVG scaling. How to combine it to immediately scale and then animate rotation?
Plunker example

I've never used Snap.svg but you might try this:
var i = 0;
function wheelAnimation(cx, cy, speed, scale){
i++;
g.attr({ transform: "r0 " + cx + " " + cy + " s" + scale + "," + scale + "," + cx + "," + cy }); //Reset + Scale setup
g.animate({
transform: "r360," + cx + "," + cy + " s" + scale + "," + scale + "," + cx + "," + cy }, // Basic rotation around a point. No frills.
speed, // Nice slow turning rays
function(){
if(i == 5)
speed = 5000;
wheelAnimation(cx, cy, speed, scale); // Repeat this animation so it appears infinite.
}
);
}
Hope this helps you :)
See Plunkr

Related

Color gradient from red to green without yellow

I have some colored text to indicate quality (red = bad, green = good).
When the quality is at 50%, the text is yellow and barely legible. Is there any way to have a gradient go from red to green without yellow in the middle?
(The quality could be any value, so setting the colors manually won't work.)
for(i=0;i<=100;i+=10) {
$('body').append('<div style="color:' + color(i/100) + '">Quality ' + i + '</div>');
}
function color(quality) {
var h = 355 + 125 * quality;
var s = 130 - 60 * quality;
var l = 60;
return 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
An alternative is this function, but it just returns an ugly brown in the middle:
for(i=0;i<=100;i+=10) {
$('body').append('<div style="color:' + color(i/100) + '">Quality ' + i + '</div>');
}
function color(quality) {
var r = 255 * (1 - quality);
var g = 255 * quality;
var b = 0;
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here's a possible way to do it using hue-rotate, but it has the dirty-brown problem rather. I'm including it because it uses a css filter rather than a css color, which might be of interest because it's a different approach. The constant 1.2 was reached by trial and error rather than calculation, so could be adjusted to taste.
for(i=0;i<=100;i+=10) {
$('body').append('<div style="color:hsl(355, 130%, 60%); filter:hue-rotate(' + i * 1.2 + 'deg)">Quality ' + i + '</div>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have modified my function to reduce the l-value the closer it gets to .5 (yellow). Obviously, the yellow is a bit muddy now, but overall I feel this is a good solution :)
for(i=0;i<=100;i+=10) {
$('body').append('<div style="color:' + color(i/100) + '">Quality ' + i + '</div>');
}
function color(quality) {
var h = 355 + 125 * quality;
var s = 130 - 60 * quality;
var l = 45 + Math.abs(0.5 - quality) * 30;
return 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

d3.js limit panning in force layout

I am using d3.js with a force layout to visualize a large number of nodes. I would like to implement a limitation to the panning option of the zoom.
JSFiddle : https://jsfiddle.net/40z5tw8h/24/
The above fiddle contains a simple version of what I am working on.
Because I would potentially have to visualize a very large dataset, I use a function to scale down the group holding element ('g') after forces are done. In that way i always have the full visualization visible afterwards.
I would like to limit the panning - when the graph is fully visible, to only be able to move it within the viewport.
In case the layout is zoomed, I would like to limit the panning as follows:
The group holding element should not be able to go:
down more than 20 px from the top of the svg.
right more than 20 px from the left side of the svg.
up more than 20 px from the bottom of the svg.
left more than 20 px from the right side of the svg.
I think all the implementation should be within the zoom function, which for now is:
function zoomed(){
if (d3.event.sourceEvent == null){ //when fitFullGraph uses the zoom
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
else{
var gElementBounds = g.node().getBoundingClientRect();
var g_bottom = gElementBounds.bottom;
var g_top = gElementBounds.top;
var g_left = gElementBounds.left;
var g_right = gElementBounds.right;
var g_height = gElementBounds.height;
var g_width = gElementBounds.width;
var svg = g.node().parentElement;
var svgElementBounds = svg.getBoundingClientRect();
var svg_bottom = svgElementBounds.bottom;
var svg_top = svgElementBounds.top;
var svg_left = svgElementBounds.left;
var svg_right = svgElementBounds.right;
var svg_height = svgElementBounds.height;
var svg_width = svgElementBounds.width;
var t = d3.event.translate;
var margin = 20;
if(d3.event.sourceEvent.type == 'wheel'){//event is zoom
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
else{//event is pan
// if(t[0] < svg_left + margin) t[0]= svg_left + margin;
//else if(t[0] > svg_width-g_width - margin) t[0] = svg_width-g_width - margin;
// if(t[1] < g_height +margin) t[1] = g_height + margin;
//else if (t[1] > svg_height - margin) t[1] = svg_height - margin;
//.attr("transform", "translate(" + t+ ")scale(" + d3.event.scale + ")");
//3.event.translate = t;
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
}
}
The limitations I tried to implement are commented out, because they do not work properly.
Does anyone have a solution?
This is not the complete answer to your question.
I used for block panning to left side translate X scale
var translate = d3.event.translate;
var translateX = translate[0];
var translateY = translate[1];
var scale = d3.event.scale;
var tX = translateX * scale;
var tY = translateY * scale;
console.log('tx', tX, 'ty', tY);
// Do not pan more to left
if (tX> 0) {
g.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
} else {
translate[0] = 0;
g.attr("transform", "translate(" + translate + ") scale(" + d3.event.scale + ")");
}
Which cancels the translation to left but internally it continues. Your user probably stops dragging to the left. Panning to the right gets weird when starting to pan as internally the event has panned far to the left.

D3.js zoom and touch device smoothness

I am using d3.behaviour.zoom on my graph and all is well on the desktop. However, when i do it on an ipad the zooming is very choppy. Is there a way I can smooth it out? It seems like i need to cancel translate calls when zooming.
I have tried a couple of things but none to any great success.
an example is in the zoom handler i get the 2 touch point x and y then get the distance between then and depending if it shrinks or grows from the last stored distance i added or subtracted 0.05 to the d3.event.scale which is used in the transform.
Is this right or am i way off and need to take something else into consideration
Help much appreciated
Cheers
Mark
EDIT:
Thought i would include some code here seeing as i cannot use another service via works network
attaching the zoom handler
RadarDraw.ZoomListener = d3.behavior.zoom().scaleExtent([1, 5]).on("zoom", zoom);
// Create the SVG element, transforming the coordinates so (0,0) is at the centre
svg = d3.select("#radarContainer").append("svg")
.attr("viewBox", "0 0 " + _config.Width + " " + _config.Height + "")
.attr("id", "chartsvg")
.attr("width", _config.Width)
.attr("height", _config.Height)
//.call(zoom)
.append("g")
.attr("id", "svgGElm")
.attr("transform", "translate(" + _config.Width / 2 + "," + ((_config.Height - _config.Voffset) / 2 + _config.Voffset) + ")")
.call(_config.RadarType != "dash" ? RadarDraw.ZoomListener : function () { });
This is the zoom handler
function zoom(){
if (d3.event.scale <= 1 || d3.event.scale >= 5) {
if (!tools.IsArcFocused) {
svg.attr("transform", "translate("
+ (d3.event.translate[0] + (_config.Width / 2)) + "," + (d3.event.translate[1] + (_config.Height / 2))
+ ")scale(" + d3.event.scale + ")");
}
//handle the zoom of arc that occurs from dblclick. this moves to arc and centers it and zooms in into it.
if (tools.IsArcFocused) {
svg.attr("transform", "translate(" + _config.Width / 2 + "," + _config.Height / 2 + ")scale(" + 5 + ")translate("
+ -RadarDraw.transPosX + "," + -RadarDraw.transPosY + ")");
}
debugInfoBar(" scale: " + d3.event.scale
+ " last distance: " + lastDistance
+ " current distance: " + currentDistance);
//detect mouse wheel
if(d3.event.sourceEvent != null)
{
if (d3.event.sourceEvent.type=='mousewheel' || d3.event.sourceEvent.type=='wheel' || d3.event.sourceEvent.type=='DOMMouseScroll')
{
//if we are zoom in on an arc only listen to zoom out command to exit the zoom
//if wheeldelta is forward and in focus mode then ignore it
if (d3.event.sourceEvent.wheelDelta > 0 && tools.IsArcFocused)
{
//make sure dots stay smallest zoomed in size
scaleDots(5);
return;
}
if (d3.event.sourceEvent.wheelDelta < 0) {
if ((tools.IsArcFocused && d3.event.scale >= 5) || (tools.IsArcFocused && d3.event.scale <= 1)) {
tools.ExitZoom(false);
}
//reset to 0,0 scale 1 as we want to zoom out fully
if (d3.event.scale <= 1 && tools.IsArcFocused)
{
svg.attr("transform", "translate(" + _config.Width / 2 + "," + _config.Height / 2 + ")scale(" + 1 + ")");
}
}
}
if (d3.event.sourceEvent.type == "mousemove" && tools.IsArcFocused)
{
d3.event.scale = 5;
scaleDots(5);
return;
}
if (d3.event.sourceEvent.type == "touchmove")
{
//need to handle zoom out via touch (like whats done with mouse wheel)
return;
}
//deal with stopping double tap and double click events via the zoom
if (d3.event.sourceEvent.type == 'dblclick' || d3.event.sourceEvent.type == 'touchstart')
{
if (typeof (d3.event.preventDefault) == "function") {
d3.event.preventDefault();
d3.event.stopPropagation();
}
return;
}
}
scaleDots(d3.event.scale);
if(tools.IsArcFocused)
previousZoomLevel = 5;
else
previousZoomLevel = 1;
return;
} else {
if (tools.IsArcFocused) {
svg.attr("transform", "translate(" + _config.Width / 2 + "," + _config.Height / 2 + ")scale(" + 5 + ")translate("
+ -RadarDraw.transPosX + "," + -RadarDraw.transPosY + ")");
}
inTouchZoom = false;
//detect forward scroll when zoomed in so it exits zoom
if(d3.event.sourceEvent != null)
{
if (d3.event.sourceEvent.type == 'mousewheel' || d3.event.sourceEvent.type == 'wheel' || d3.event.sourceEvent.type == 'DOMMouseScroll') {
if (d3.event.sourceEvent.wheelDelta == 120)
{
d3.event.scale += 0.05;
if (d3.event.scale > 4.9)
d3.event.scale = 4.9;
}
else if (d3.event.sourceEvent.wheelDelta -= 120)
{
d3.event.scale -= 0.05;
if (d3.event.scale < 1)
d3.event.scale = 1;
}
//previousZoomLevel -gets confused sometimes and is 1 when it should be >=5
if (tools.IsArcFocused && previousZoomLevel >= 5) {
tools.ExitZoom(false);
previousZoomLevel = d3.event.scale;
}
}
if (d3.event.sourceEvent.type == "touchmove") {
//if only one touch point then do translation for pan otherwise leave as is
if (d3.event.sourceEvent.touches.length > 1) {
inTouchZoom = true;
//dont update translate use what was take before
d3.event.translate = touchZoomTranslate;
//we have atleast 2 points so use the first 2
var currentDistance = PointDistance(d3.event.sourceEvent.touches[0].pageX, d3.event.sourceEvent.touches[0].pageY, d3.event.sourceEvent.touches[1].pageX, d3.event.sourceEvent.touches[1].pageY);
debugInfoBar(" scale: " + d3.event.scale
+ " tp1 X: " + d3.event.sourceEvent.touches[0].pageX + " tp1Y: " + d3.event.sourceEvent.touches[0].pageY
+ " tp2 X: " + d3.event.sourceEvent.touches[1].pageX + " tp2Y: " + d3.event.sourceEvent.touches[1].pageY
+ " last distance: " + lastDistance
+ " current distance: " + currentDistance);
if (currentDistance > lastDistance) {
d3.event.scale += 0.05;
if(d3.event.scale > 4.9)
d3.event.scale = 4.9;
lastDistance = currentDistance;
}
else {
d3.event.scale -= 0.05;
if (d3.event.scale < 1)
d3.event.scale = 1;
lastDistance = currentDistance;
}
svg.attr("transform", "translate(" + _config.Width / 2 + "," + _config.Height / 2 + ")scale(" + d3.event.scale + ")");
return;
}
}
if (d3.event.sourceEvent.type == "touchend") {
//wipe last distance and we have finished touch
lastDistance = 0;
}
//deal with stopping double tap and double click events via the zoom
if (d3.event.sourceEvent.type == 'dblclick' || (d3.event.sourceEvent.type == 'touchstart' && !inTouchZoom))
{
if (typeof (d3.event.preventDefault) == "function") {
d3.event.preventDefault();
d3.event.stopPropagation();
}
return;
}
}
if (!tools.IsArcFocused) {
svg.attr("transform", "translate("
+ (d3.event.translate[0] + (_config.Width / 2)) + "," + (d3.event.translate[1] + (_config.Height / 2))
+ ")scale(" + d3.event.scale + ")");
}
if (d3.event.scale > 1)
previousZoom = true;
//if we are zoomed in and our previous zoom level is 5 or above then exit zoom (we are either scrolling out or pinching out of zoom)
if (tools.IsArcFocused && previousZoomLevel >= 5) {
tools.ExitZoom(false);
}
scaleDots(d3.event.scale);
}
if (d3.event.scale > 4.9)
d3.event.scale = 4.9;
if(!inTouchZoom)
touchZoomTranslate = d3.event.translate;
}
I corrected this issue by rewriting the zoom handler so it had specific touch input update, where I deal with zooming and not relying on d3. I also listened for a touchend event in zoom but it did not fire I had to attach another handler for zoomend and detect it that way
The zooming can be achieved without all the calculations.
var onZoom = function() {
var scale = d3.event.scale,
translate = d3.event.translate;
elemToZoom.attr('transform', 'scale(' + scale + ')translate(' + translate + ')');
};
var zoom = d3.behavior.zoom().on('zoom', onZoom);
var elemToZoom = d3.select('#zoomable')
.call(zoom);
When you are zooming in the graph, you may have to redraw the axes and the vertical and horizontal lines so that they don't get zoomed too.

SVG Scale without moving location

What I'm trying to do is simple: scale some SVG dots from scale(0) to scale(1) when a sibling element is hovered using vanilla js. They are the red ones in the demo
Here's the basic SVG setup
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px" y="0px" viewBox="0 0 720 576" style="enable-background:new 0 0 720 576;" xml:space="preserve">
<style type="text/css">
.st3 {
fill:red;
}
* {
-webkit-transition:.3s;
transition:.3s;
}
</style>
<g id="Layer_4">
<!-- Shield -->
<path class="st8" d="M601,304.7c-32.4-15.4-68.6-24-106.8-24c-40.4,0-78.5,9.6-112.3,26.6c4.9,79.7,41.9,146.7,109.5,187.6
C559.8,454.1,597,385.6,601,304.7z" />
<path class="st9" d="M420.1,328.7c2.1-4.7,32.5-23.9,72.5-23.9c39.9,0,73.1,20,75.5,24.3c2.4,4.3,5.7,40-12.7,74.6
c-19.7,36.9-53.5,50.1-61.8,50.4c-6.4,0.2-41.8-14.3-62.5-51.6C411.5,367.4,418,333.4,420.1,328.7z" />
<circle class="st10" cx="494.9" cy="373.3" r="35.5" />
</g>
<g id="Layer_8">
<!-- Dots on shield -->
<circle class="st3" cx="578.8" cy="316.2" r="4.6" />
<circle class="st3" cx="543.4" cy="346.2" r="4.6" />
<circle class="st3" cx="505" cy="375.5" r="4.6" />
</g>
</svg>
The issue is that SVG scales based on the origin location, not the current location, thus when a transform is applied it moves the element in addition to scaling it. I am attempting to fix this situation by translating by the BBox() offset, scaling, then translating back but that only seemed to help and not entirely fix the issue.
var shield = document.getElementById("Layer_4"),
dots = document.querySelectorAll("#Layer_8 .st3");
toggleTransform(false);
shield.onmouseover = function () { toggleTransform(true); }
shield.onmouseout = function () { toggleTransform(false); }
function toggleTransform(bool) {
if (!bool) {
for (var i = 0; i < dots.length; i++) {
var box = dots[i].getBBox(),
cx = box.x + box.width / 10,
cy = box.y + box.height / 10;
//dots[i].setAttribute("transform", "translate(" + cx + " " + cy + ") scale(0) translate(" + cx + " " + cy + ")");
dots[i].style.WebkitTransform = "translate(" + cx + "px, " + cy + "px) scale(0) translate(" + -cx + "px, " + -cy + "px)";
}
} else {
for (var i = 0; i < dots.length; i++) {
var box = dots[i].getBBox(),
cx = box.x + box.width / 2,
cy = box.y + box.height / 2;
//dots[i].setAttribute("transform", "translate(0 0) scale(1) translate(0 0)");
dots[i].style.WebkitTransform = "translate(0, 0) scale(1) translate(0, 0)";
}
}
}
I tried using both setAttribute and CSS's transform (I couldn't get setAttribute to transition, presumably because it's not animatable by CSS) but couldn't get it with either. I've only been testing in Chrome
Anyone have an idea how I can scale, while not moving, red dots?
Here's the demo again if you missed it
Edit
I made a function based on RashFlash's answer to make it quite simple to use and also takes into account offsets and different transform origins
function scaleMe(elem, scaleX, scaleY, newOffsetX, newOffsetY, originX, originY) {
newOffsetX = null ? 0 : newOffsetX;
newOffsetY = null ? 0 : newOffsetY;
originX = null ? "center" : originX;
originY = null ? "center" : originY;
var bbox = elem.getBBox(),
cx = bbox.x + (bbox.width / 2),
cy = bbox.y + (bbox.height / 2),
tx = -cx * (scaleX - 1) + newOffsetX,
ty = -cy * (scaleY - 1) + newOffsetY;
if(originX === "left" || originX === "right") {
tx = newOffsetX;
}
if(originY === "top" || originY === "bottom") {
ty = newOffsetY;
}
var scalestr = scaleX + ',' + scaleY,
translatestr = tx + 'px,' + ty + 'px';
elem.style.WebkitTransformOrigin = originX + " " + originY;
elem.style.MozTransformOrigin = originX + " " + originY;
elem.style.msTransformOrigin = originX + " " + originY;
elem.style.transformOrigin = originX + " " + originY;
elem.style.WebkitTransform = "translate(" + translatestr + ") scale(" + scalestr + ")";
elem.style.MozTransform = "translate(" + translatestr + ") scale(" + scalestr + ")";
elem.style.msTransform = "translate(" + translatestr + ") scale(" + scalestr + ")";
elem.style.transform = "translate(" + translatestr + ") scale(" + scalestr + ")";
}
Updated to work with modern browsers that support transform-box
Previously, this approach worked only in Chrome. But spec changes to how transform-origin works, and the addition of transform-box now means that this works in more browsers (currently Chrome, FF, and Opera).
You can actually achieve this effect without JS.
.st3 {
fill: red;
-webkit-transform: scale(1);
-webkit-transform-origin: 50% 50%;
-webkit-transition:.3s;
transform: scale(1);
transform-origin: 50% 50%;
transition:.3s;
transform-box: fill-box;
}
#Layer_4:hover + g .st3 {
-webkit-transform: scale(2);
-webkit-transform-origin: 50% 50%;
-webkit-transition:.3s;
transform: scale(2);
transform-origin: 50% 50%;
transition:.3s;
}
Demo here
if i am not wrong, you want to scale the dots along their center, dots remain their current position and just gets bigger.
if this you want, then following code will help you
var bbox=elementNode.getBBox();
var cx=bbox.x+(bbox.width/2),
cy=bbox.y+(bbox.height/2); // finding center of element
var scalex=1.5, scaley=1.5; // your desired scale
var saclestr=scalex+','+scaley;
var tx=-cx*(scalex-1);
var ty=-cy*(scaley-1);
var translatestr=tx+','+ty;
elementNode.setAttribute('transform','translate('+translatestr+') scale('+saclestr+')');
So what i did, i first translate the dot and than scale it. i use following formula as described in
Transforming Coordinate system
translate(-centerX*(factor-1), -centerY*(factor-1))
scale(factor)
An easier way to do this that does not involve a bunch of geometry is to put the item to be scaled and translated into a parent group ('g').
Then, you apply the translation to the parent group and the scale to the element itself.
var trasnstr = x + ',' + y;
var scalestr = scaleX + ',' + scaleY;
parentElement.setAttribute('transform', 'translate(' + trasnstr + ')');
element.setAttribute('transform', 'scale(' + scalestr + ')');
This will automatically calculate and set transform-origin for any SVG element.
// mainSvgElement is SVG element itself
// svgChildElement is any path, rect, circle etc. inside SVG element
var setTransformOrigin = function(mainSvgElement, svgChildElement) {
var mainRect = mainSvgElement.getBoundingClientRect();
var childRect = svgChildElement.getBoundingClientRect();
var originX = (((childRect.left - mainRect.left) + (childRect.width * 0.5)) / mainRect.width) * 100;
var originY = (((childRect.top - mainRect.top) + (childRect.height * 0.5)) / mainRect.height) * 100;
svgChildElement.style.transformOrigin = originX + "% " + originY + "%";
};
setTransformOrigin(mainSvgElement, svgChildElement);
// set scale now / or you can set in css too
svgChildElement.style.transform = "scale(1.5)";
(function() {
var mainSvgElement = document.querySelector("svg");
var svgChildElement = mainSvgElement.querySelector("path");
// mainSvgElement is SVG element itself
// svgChildElement is any path, rect, circle etc. inside SVG element
var setTransformOrigin = function(mainSvgElement, svgChildElement) {
var mainRect = mainSvgElement.getBoundingClientRect();
var childRect = svgChildElement.getBoundingClientRect();
var originX = (((childRect.left - mainRect.left) + (childRect.width * 0.5)) / mainRect.width) * 100;
var originY = (((childRect.top - mainRect.top) + (childRect.height * 0.5)) / mainRect.height) * 100;
svgChildElement.style.transformOrigin = originX + "% " + originY + "%";
};
setTransformOrigin(mainSvgElement, svgChildElement);
// set scale now / or you can set in css too
svgChildElement.addEventListener("mouseenter", function() {
svgChildElement.style.transform = "scale(1.5)";
});
svgChildElement.addEventListener("mouseleave", function() {
svgChildElement.style.transform = "scale(1)";
});
})();
svg {
width: 100%;
border: 2px solid red;
}
path {
cursor: pointer;
transition: transform 1s;
}
Bring your mouse over on the shape:
<svg class="tb-graph" viewBox="0 0 1006 684" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M574.618 66.3322C575.377 63.1066 573.378 59.87 570.137 59.1784C512.776 46.9376 452.991 52.4821 398.793 75.1494C344.594 97.8167 298.663 136.486 267.096 185.919C265.312 188.711 266.213 192.407 269.042 194.132L357.225 247.895C360.055 249.62 363.738 248.718 365.56 245.95C384.451 217.254 411.493 194.793 443.273 181.502C475.052 168.211 510.032 164.732 543.728 171.435C546.978 172.082 550.207 170.093 550.966 166.867L574.618 66.3322Z" fill="#005453" stroke="#012020" stroke-width="2" />
https://codepen.io/animatedcreativity/pen/qBKXQKZ

jquery .css() not applying -webkit-transform

I cannot see what is wrong with this code. Calculate center position of window then transform-translate div there (have to use translate for what i am doing).
Just getting this working for Chrome for a start, hence the -webkit- prefix).
Very confused as to why jQuery does not apply the inline style to the .logo div. Have included my other trouble-shooting experiments, commented out.
A syntax problem? jsfiddle here.
var centerPosition = '';
function centerLogo(){
var w_width = $(window).width();
var w_height = $(window).height();
var hCenter = (w_width / 2) - 150;
var vCenter = (w_height / 2) - 150;
console.log(hCenter);
console.log(vCenter);
var centerPosition = 'translate(' + hCenter + 'px, ' + vCenter + 'px);';
console.log(centerPosition);
$('.logo').css('-webkit-transform', centerPosition);
// Try uncommenting the three examples below - they all work ...
// $('.logo').css('background', 'blue');
// centerPosition = 'blue';
// $('.logo').css('background', centerPosition);
// $('.logo').css('-webkit-transform', 'translate(10.85px, 45.56px)');
}
jQuery(document).ready(function($){
centerLogo();
});
The correcy syntax of $('.logo').css('-webkit-transform', centerPosition); does not have semi colons inside the Strings. Try changing this:
var centerPosition = 'translate(' + hCenter + 'px, ' + vCenter + 'px);';
to this:
var centerPosition = 'translate(' + hCenter + 'px, ' + vCenter + 'px)';
Should work: http://jsfiddle.net/7f7rt/6/
This Will Sure Work.
var posElem = document.getElementById('logo'); // set id to div
var newStyle = '-webkit-transform: translate(' + hCenter + 'px, ' + vCenter + 'px);' +
'transform: translate(' + hCenter + 'px, ' + vCenter + 'px);';
posElem.setAttribute('style',newStyle);

Categories

Resources