草庐IT

javascript - 将复杂的 svg 形状转换为圆形抽象

coder 2023-08-03 原文

SVG 很丑,请查看我的:

JSFIDDLE LINK

HTML:

<svg version="1.1" class="overlap-svg" id="alaska"></svg>
<svg version="1.1" class="overlap-svg" id="grid"></svg>

CSS:

.overlap-svg {
    position: absolute;
    left:0;
    top: 0;
}

问题:

如果我们重叠这 2 个 svg,JS 函数是什么来突出显示其中包含阿拉斯加(红色)部分的 svg 圆圈?

查看下面的描述以获取更多信息


  1. 假设您有一个复杂的形状,例如阿拉斯加的轮廓。

  1. 假设您有另一个 svg 圆网格:


我如何转换它:

像这样:

如果阿拉斯加(红色)的任何部分在圆圈区域内,则圆圈应填充为红色。

请再次查看我上面的 JSFiddle 链接。

最佳答案

fiddle

您可以获取 svg 并将其加载到 Canvas 元素中。获取该元素,因为它是一个 Canvas 元素,所以您可以获得它的像素数组。

可以通过从适当调整大小的 Canvas 的像素构建网格来构建您的圆形抽象。

首先是一个助手:网格管理器。

function GridManager(configIn) {
  var gm_ = {};

  gm_.config = {
    'gridWidth': 10,
    'gridHeight': 10,
    'gridCellWidth': 10,
    'gridCellHeight': 10,
    'gridHeight': 100,
    'dataSrc': []
  };

  // Load new config over defaults
  for (var property in configIn) {
    gm_.config[property] = configIn[property];
  }

  /** 
    * Creates an array using the module's config building a 2d data array 
    * from a flat array. Loops over GridManager.config.dataSrc
    * 
    * Render a checkerboard pattern:
    *   GridManager.config.dataSrc = ["#"," "]
    * 
    * Render you can load a image by passing in its full pixel array, 
    * provided image height and width match GridManager.config.gridHeight
    * and GridManager.config.gridWidth. 
    */
  gm_.createGridSrc = function() {
    var height = this.config.gridHeight;
    var width = this.config.gridWidth;
    var output = [];

    for (var i = 0; i < height; i++) {
      output[i] = [];

      for (var ii = 0; ii < width; ii++) {
        if (this.config.dataSrc !== undefined) {
          var dataSrc = this.config.dataSrc;
          output[i][ii] = dataSrc[i*width + ii % dataSrc.length];
        }
      }
    }
    return output;
  };

  /** 
    * Creates a SVG with a grid of circles based on
    * GridManager.config.dataSrc.
    * 
    * This is where you can customize GridManager output.
    */
  gm_.createSvgGrid = function() {
    var cellWidth = this.config.gridCellWidth;
    var cellHeight = this.config.gridCellHeight;
    var svgWidth = 1000;
    var svgHeight = 1000;
    var radius = 3
    var cellOffset = radius / 2;

    //create svg
    var xmlns = 'http://www.w3.org/2000/svg';
    var svgElem = document.createElementNS (xmlns, 'svg');
    svgElem.setAttributeNS (null, 'viewBox', '0 0 ' + svgWidth + ' ' + svgHeight);
    svgElem.setAttributeNS (null, 'width', svgWidth);
    svgElem.setAttributeNS (null, 'height', svgHeight);
    svgElem.style.display = 'block';

    //create wrapper path
    var g = document.createElementNS (xmlns, 'g');
    svgElem.appendChild (g);

    //create grid
    var data = this.createGridSrc();
    var count = 0;
    for (var i = data.length - 1; i >= 0; i--) {
      for (var ii = data[i].length - 1; ii >= 0; ii--) {
        
        // This svgHeight and svgWidth subtraction here flips the image over
        // perhaps this should be accomplished elsewhere.
        var y = svgHeight - (cellHeight * i) - cellOffset;
        var x = svgWidth - (cellWidth * ii) - cellOffset;

        var cell = document.createElementNS (xmlns, 'circle');
        var template = data[i][ii];
        
        // Machine has averaged the amount of fill per pixel
        // from 0 - 255, so you can filter just the red pixels like this
        // over a certain strength.
        if (template[0] > 10 ) {
          cell.setAttributeNS (null, 'fill', '#ff0000');
          // Consider stashing refs to these in this.groups['red'] or something
          // similar
        } else {
          cell.setAttributeNS (null, 'fill', 'none');
        }

        cell.setAttributeNS (null, 'stroke', '#000000');
        cell.setAttributeNS (null, 'stroke-miterlimit', '#10');
        cell.setAttributeNS (null, 'cx', x);
        cell.setAttributeNS (null, 'cy', y);
        cell.setAttributeNS (null, 'r', radius);

        g.appendChild (cell);
      }
    }
    return svgElem;
  }
  return gm_;
}

然后在 main.js 中

var wrapper = document.getElementById('wrapper');

var mySVG = document.getElementById('alaska').outerHTML;

mySVG = mySVG.slice(0, 4) + ' height="100" ' + mySVG.slice(4);

// Create a Data URI based on the #alaska element.
var mySrc = 'data:image/svg+xml;base64,' + window.btoa(mySVG);

// Create a new image to do our resizing and capture our pixel data from.
var source = new Image();
source.onload = function() {

  var svgRasterStage = document.createElement('canvas');
  svgRasterStage.width = 1000;
  svgRasterStage.height = 1000;

  svgRasterStage.classList.add('hidden');

  // You may not need this at all, I didn't test it.
  wrapper.appendChild(svgRasterStage);

  // Get drawing context for the Canvas
  var svgRasterStageContext = svgRasterStage.getContext('2d');

  // Draw the SVG to the stage.
  svgRasterStageContext.drawImage(source, 0, 0);
  
  // We can now get array of rgba pixels all concatinated together:
  //    [ r, g, b, a, r, g, b, a,  (...)  r, g, b, a, r, g, b, a]
  var rgbaConcat = svgRasterStageContext.getImageData(0, 0, 100, 100).data;

  // Which sucks, so here's a way to convert them to pixels that we can 
  // use with GridManager.createSvgGrid.
  var pixels = [];
  var count = 0;
  
  // NOTE: this is a for with a weird step: i=i-4. i-4 is an infinte loop.
  // anything else just jumbles the pixels.
  for (var i = rgbaConcat.length - 1; i >= 0; i=i-4) {
    var r = rgbaConcat[i - 0];
    var g = rgbaConcat[i - 1];
    var b = rgbaConcat[i - 2];
    var a = rgbaConcat[i - 3];
    pixels.push([r, g, b, a]);
  }

  // We create our GridManager (finally).
  var gm = new GridManager({
    'gridWidth': 100,
    'gridHeight': 100,
    'dataSrc': pixels
  });
  
  // And let her rip!
  wrapper.appendChild(gm.createSvgGrid());
}

关于javascript - 将复杂的 svg 形状转换为圆形抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158918/

有关javascript - 将复杂的 svg 形状转换为圆形抽象的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  4. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  5. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  6. ruby-on-rails - 使用 ruby​​ 将多个实例变量转换为散列的更好方法? - 2

    我收到格式为的回复#我需要将其转换为哈希值(针对活跃商家)。目前我正在遍历变量并执行此操作:response.instance_variables.eachdo|r|my_hash.merge!(r.to_s.delete("@").intern=>response.instance_eval(r.to_s.delete("@")))end这有效,它将生成{:first="charlie",:last=>"kelly"},但它似乎有点hacky和不稳定。有更好的方法吗?编辑:我刚刚意识到我可以使用instance_variable_get作为该等式的第二部分,但这仍然是主要问题。

  7. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

  8. ruby-on-rails - 将字符串转换为 ruby​​-on-rails 中的函数 - 2

    我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。

  9. ruby-on-rails - 将 ruby​​ 数组转换为整齐的列字符串? - 2

    我是ruby​​的新手,我正在尝试制作一个程序来自动格式化给定的字符串和数组。我试图弄清楚的一种自动格式化功能是一种用于数组的功能。假设我有一个如下例所示的数组myArray=["a","b","c"]我想把它变成一个列化的字符串,这样putsmyString就会给出`1)a``2)b``3)c`我该怎么做呢?我能找到的最接近的东西是使用.each这不是我想要的,我不能让每一行都有一个单独的条目。这一切都必须是一个带有换行符的字符串。任何帮助将不胜感激,提前致谢 最佳答案 您可以使用.map与.with_index:myArray=

  10. ruby - 使用 AES 的 Rails 加密,过于复杂 - 2

    我在加密来self正在使用的第三方供应商的值时遇到问题。他们的指令如下:1)Converttheencryptionpasswordtoabytearray.2)Convertthevaluetobeencryptedtoabytearray.3)Theentirelengthofthearrayisinsertedasthefirstfourbytesontothefrontofthefirstblockoftheresultantbytearraybeforeencryption.4)EncryptthevalueusingAESwith:1.256-bitkeysize,2.25

随机推荐