学习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>
并将其放在画布上。
最简单的方法是将图形保留在单独的画布上。仅将主画布用作最终显示。
将绘图与显示画布分开后,即可开始对视觉效果FX进行分层。
要勾勒出像素艺术图像,请创建图像的可绘制副本。
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, 0);
ctx.drawImage(image, 0, -1);
ctx.drawImage(image, 0, 1);
ctx.fillStyle = color;
ctx.globalCompositeOperation = "source-atop";
ctx.fillRect(0,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, 0);
// then the pixels
ctx.drawImage(myArt, 0, 0);
您还可以折叠图层以使轮廓永久
ctx.globalCompositeOperation = "destination-over";
myArt.ctx.drawImage(outline, 0, 0);
ctx.globalCompositeOperation = "source-over"; // restore default
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句