SOURCE

console 命令行工具 X clear

                    
>
console
import { Rect } from "zrender"

interface IPoint {
  x: number
  y: number
}

interface IPixelSize {
  width: number
  height: number
}

function pixelStyle(color = "#000000"): unknown {
  return {
    fill: color,
    stroke: color
  }
}

function generatePixel(point = { x: 0, y: 0 }, color = "#000000", pixelSize = { width: 16, height: 16 }): Rect {
  return new Rect({
    shape: {
      x: point.x * pixelSize.width,
      y: point.y * pixelSize.height,
      width: pixelSize.width,
      height: pixelSize.height
    },
    style: pixelStyle(color)
  })
}

function generatePixelList(points: IPoint[], color = "#000000", pixelSize = { width: 16, height: 16 }): Rect[] {
  return points.map(point => generatePixel(point, color, pixelSize))
}

function computeLinePoints(p1: IPoint, p2: IPoint): IPoint[] {
  const points: IPoint[] = []

  if (p1.x === p2.x) {
    const min = Math.min(p1.y, p2.y)
    const max = Math.max(p1.y, p2.y)
    for (let j = min; j <= max; j++) {
      points.push({ x: p1.x, y: j })
    }
  } else {
    const dy = p2.y - p1.y
    const dx = p2.x - p1.x
    const m = dy / dx
    const c = p1.y - (m * p1.x)
    if (Math.abs(dx) >= Math.abs(dy)) {
      const min = Math.min(p1.x, p2.x)
      const max = Math.max(p1.x, p2.x)
      for (let i = min; i <= max; i++) {
        const j = Math.round((m * i) + c)
        points.push({ x: i, y: j })
      }
    } else {
      const min = Math.min(p1.y, p2.y)
      const max = Math.max(p1.y, p2.y)
      for (let j = min; j <= max; j++) {
        const i = Math.round((j - c) / m)
        points.push({ x: i, y: j })
      }
    }
  }

  return points
}

function drawLine(p1: IPoint, p2: IPoint, color = "#000000", pixelSize = { width: 16, height: 16 }): Rect[] {
  const points = computeLinePoints(p1, p2)
  return generatePixelList(points, color, pixelSize)
}
<canvas id="ok" width="384" height="576"></canvas>

<script>
    const zr = zrender.init(document.getElementById("ok"))

    const gridGroup = new zrender.Group()
    const pointGroup = new zrender.Group()
    zr.add(gridGroup)
    zr.add(pointGroup)

    const screenColumn = 24
    const screenRow = 36
    const tileSize = 16
    const canvasWidth = screenColumn * tileSize
    const canvasHeight = screenRow * tileSize
    const gridColor = '#AAA'

    for (let h = 0; h <= screenColumn; h++) {
        const vLine = new zrender.Line({
            shape: {
                x1: h * tileSize,
                y1: 0,
                x2: h * tileSize,
                y2: canvasHeight
            }
        })
        gridGroup.add(vLine)
    }

    for (let v = 0; v <= screenRow; v++) {
        const hLine = new zrender.Line({
            shape: {
                x1: 0,
                y1: v * tileSize,
                x2: canvasWidth,
                y2: v * tileSize
            }
        })
        gridGroup.add(hLine)
    }
</script>
canvas#ok {
    background: #eee;
}

本项目引用的自定义外部资源