简体   繁体   中英

How do i animate the fill of an inline svg to change with mouse position (in parent div)

是否可以设置内联svg路径的动画,并随着鼠标在页面上的移动而改变?

In the example in the code snippet below, the x and y positions of the mouse are monitored using the "mousemove" event and the screenX and screenY properties of the event object. Red and green colors values are set depending on those coordinates, and an rgb fill color string is constructed and imposed on an SVG path element.

 var path = document.querySelector("path"); document.body.addEventListener("mousemove", function(evt) { var xRatio = Math.min(1, evt.clientX / document.body.offsetWidth ); var yRatio = Math.min(1, evt.clientY / document.body.offsetHeight); var red = parseInt(255 * xRatio); var green = parseInt(255 * yRatio); var color = "rgb(" + red + ", " + green + ", 128)"; document.querySelector("path").setAttribute("fill", color); }); 
 body { border: solid black 1px; padding: 0.5em; } p { margin: 0; } 
 <body> <p>Move your mouse over the image to see the colour-change effect.</p> <svg width="400" height="150"> <path d="M10,75 C200,-100 300,120 390,75 200,250 100,30 10,75" stroke="black" stroke-width="4" fill="none" /> </svg> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM