HTML5 <canvas>元素上像素之间的网格线

问题描述

在学习JS的同时,我正在开发一个简单的像素艺术程序,就像一个有趣的项目一样。 我希望画布上的每个像素都被1px边框包围。 我唯一的想法是创建一个覆盖网格并调整其大小以适合画布像素。 例如:

<div 
  class="grid" 
  style="width: (canvas width); height: (canvas height); background-image: (transparent image with 1px border); background-size: (size of each canvas pixel); pointer-events: none;"
></div>
<br>

并将其放在画布上。

解决方法

在内存画布中使用许多作为图层

最简单的方法是将图形保留在单独的画布上。只能将主画布用作最终显示。

一旦将绘图与显示画布分开,就可以开始对视觉效果进行分层。

要复制图像(画布,jpeg,png等)

要概述像素艺术图像,请创建图像的可绘制副本。

function copyImage(image){
    const copy = document.createElement("canvas");
    copy.width = image.width;
    copy.height = image.height;
    copy.ctx = copy.getContext("2d");
    copy.ctx.drawImage(image);
    return copy;
}

创建空白画布层

function createImage(w,h){
    const img = document.createElement("canvas");
    img.width = w;
    img.height = h;
    img.ctx = img.getContext("2d");
    return img;
}

概述层

在其自身上方向左1个像素,向右1个,上方1个和下方1个像素绘制该副本。然后设置轮廓线颜色

function outlineLayer(image,color) {
    const ctx = image.ctx;
    ctx.globalCompositeOperation = "source-over";
    ctx.drawImage(image,-1,0);
    ctx.drawImage(image,1,-1);
    ctx.drawImage(image,1);

    ctx.fillStyle = color;
    ctx.globalCompositeOperation = "source-atop";
    ctx.fillRect(0,image.width,image.height);

    ctx.globalCompositeOperation = "source-over";
}

渲染

渲染图像时,首先在图像之前绘制轮廓线层。

使用以上功能

// ctx is the context of the visual (on page) canvas
// myArt is a drawing. It is a canvas that is kept in memory and not on the page.
const outline = copyImage(myArt);
outlineLayer(outline,"black");

// then draw both on the main canvas
// First outline
ctx.drawImage(outline,0);
// then the pixels
ctx.drawImage(myArt,0);

折叠层

您还可以折叠图层以使轮廓永久化

ctx.globalCompositeOperation = "destination-over";
myArt.ctx.drawImage(outline,0);
ctx.globalCompositeOperation = "source-over"; // restore default




 

   
,

如果您想在画布周围使用边框/轮廓,请尝试以下操作:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>