簡體   English   中英

如何從 javascript 中的 1 和 0 的二維數組創建圖像?

[英]How to create image from a 2D array of 1's and 0's in javascript?

我有一個 1 和 0 的二維數組,我想在我的反應應用程序中從該數組創建一個黑白圖像。

我的數組看起來像這樣,但更大:

var items = [
  [0, 1, 1, 0],
  [1, 1, 1, 0],
  [0, 1, 0, 1]
];

我想展示類似的東西: 在此處輸入圖像描述

如何在我的反應應用程序中從我的陣列中 output 黑白光柵 plot ?

使用兩個嵌套循環遍歷每一行和一行中的每個項目。 然后有條件地渲染元素(例如<div> )並相應地設置它們的樣式。 給出一個想法,道具matrix是你的二維數組。

const Raster = ({matrix}) => {
  return (
    <>
      {matrix.forEach(row => {
        return (
          <div>
            {row.forEach(item => {
              return (
                <div
                  style={{
                    height: 50,
                    width: 50,
                    backgroundColor: 0 === item ? "white" : "black"
                  }}
                ></div>
              );
            })}
          </div>
        );
      })}
    </>
  );
};

您可以使用渲染 PNG 或其他圖像格式的庫,但由於您有一個簡單的像素列表,因此 SVG 圖像也不難渲染。 從技術上講,這不是光柵 plot,因為它是矢量圖像,但如果您願意,您可以將其渲染為 4x3 像素,並且它會保持清晰。

 function drawSvg(tag, rows) { // If you're sure all rows are always the same size, it's // faster and simpler to just do `rows[0].length`. const pixelWidth = rows.reduce((max, row) => Math.max(max, row.length), 0); const pixelHeight = rows.length; // The `viewBox` of a SVG tag is the viewport to draw to. // Since we want 1 "pixel" in our vector to be 1 pixel in the output, // the viewbox will be 0 -0.5 4 3 for our 4x3 sample image. // The -0.5 shift upwards is because of how SVG aligns things. tag.setAttribute('viewBox', `0 -0.5 ${pixelWidth} ${pixelHeight}`); // The width/height of a SVG tag can be overwritten by CSS to your liking, // but having them makes sure the image stays the correct aspect ratio. tag.setAttribute('width', pixelWidth); tag.setAttribute('height', pixelHeight); const path = tag.querySelector('path'); let data = ''; for (let line = 0; line < rows.length; line++) { // [M]ove absolutely to 0,Y data += ` M0,${line}`; const row = rows[line]; for (const pixel of row) { if (pixel) { // Draw a [h]orizontal line, 1 unit wide. data += ` h1`; } else { // [m]ove relatively to +1,+0. data += ` m1,0`; } } } // Output will be something like 'M0,0 h1 m1,0 h1'. path.setAttribute('d', data); // You can also create a link to a SVG by embedding it as a data URL. // encodeURIComponent is smaller than Base64Encode. // You could minify the input, but we don't need to bother for the sample. const href = `data:image/svg+xml,${encodeURIComponent(tag.outerHTML)}`; // Create an <img src=""> const img = document.createElement('img'); img.classList.add('output'); img.setAttribute('src', href); tag.parentNode.insertBefore(img, tag); // Works as a background image, too. const div = document.createElement('div'); div.classList.add('output'); div.style.backgroundImage = `url("${href}")`; tag.parentNode.insertBefore(div, tag); } addEventListener('DOMContentLoaded', () => { drawSvg(document.querySelector('svg.output'), [ [0, 1, 1, 0], [1, 1, 1, 0], [0, 1, 0, 1] ]); });
 .output { width: 100px; height: auto; border: 1px solid orange; } img.output { border-color: lime; } div.output { background: no-repeat 0 0; background-size: cover; height: 75px; border-color: aqua; }
 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1" shape-rendering="crispEdges" class="output"> <path fill="none" stroke="#000000" d="M0" /> </svg>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM