简体   繁体   中英

How can you target part of svg image

svg的例子

So I have this similar svg image. white being transparent with black dots. I have to cover the whole background with this pattern and then target a 5x5square dot area of dots to change their color.

What is the simplest way or a common method to achieve this?

You can access elements of an SVG-image if it is embedded directly into the HTML-code. You can even create the whole SVG using JavaScript. Here is an example: https://jsfiddle.net/da_mkay/eyskzpsc/7/

<!DOCTYPE html>
<html>
<head>
<title>SVG dots</title>
</head>
<body>
</body>

<script>
var makeSVGElement = function (tag, attrs) {
  var element = document.createElementNS('http://www.w3.org/2000/svg', tag)
  for (var k in attrs) {
    element.setAttribute(k, attrs[k])
  }
  return element
}


var makeDotSVG = function (width, height, dotRadius) {
  var svg = makeSVGElement('svg', { width: width, height: height, 'class': 'dot-svg' })
    , dotDiameter = dotRadius*2
    , dotsX = Math.floor(width / dotDiameter)
    , dotsY = Math.floor(height / dotDiameter)

  // Fill complete SVG canvas with dots
  for (var x = 0; x < dotsX; x++) {
    for (var y = 0; y < dotsY; y++) {
      var dot = makeSVGElement('circle', {
        id: 'dot-'+x+'-'+y,
        cx: dotRadius + x*dotDiameter,
        cy: dotRadius + y*dotDiameter,
        r: dotRadius,
        fill: '#B3E3A3'
      })
      svg.appendChild(dot)
    }
  }

  // Highlight the hovered dots by changing its fill-color
  var curMouseOver = function (event) {
    var dotX = Math.floor(event.offsetX / dotDiameter)
      , dotY = Math.floor(event.offsetY / dotDiameter)
      , dot = svg.getElementById('dot-'+dotX+'-'+dotY)
    if (dot !== null) {
      dot.setAttribute('fill', '#73B85C')
    }
  }

  svg.addEventListener('mouseover', curMouseOver)

  return svg
}

// Create SVG and add to body
var myDotSVG = makeDotSVG(500, 500, 5)
console.log(document.body)
document.body.appendChild(myDotSVG)
</script>
</html>

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