画布上下文可以用笔画(moveTo,lineTo)绘制像素,基本上可以使其长1像素。虽然现在我不得不为1做两个动作,但看起来。另外,我想要的基本上是预先创建我自己的像素图像。
例如,假设我们要创建以下图像:

20x20为此,我希望对20x20像素空间执行以下操作:赋值(行、列);(0、0)、(0、17)、(1、9)等(直到19.19)为白色。其余的将默认为另一种选定的颜色(或作为画布背景);黑色。
我想要创建一个循环,或者放入一个预先确定的公式或一个随机算法来分配像素。基本上,传递一些要运行的函数,或者将像素分配到“创建像素图像”函数中,以创建一个图像,我可以将其放在上下文中并显示在画布上。作为一个额外的,我也可以平移,旋转,倾斜等这个形象,因为我有完全控制。
发布于 2022-10-07 20:29:27
drawRect),它基本上在画布内的x,y坐标处创建一个大小的矩形。x, y, w, h, color数组drawRect函数的数组
const drawRect = (ctx, x, y, w=1, h=1, color="#fff") => {
ctx.fillStyle = color;
ctx.fillRect(x, y, w, h);
};
const size = 20;
const ctx = document.querySelector("#cvs").getContext("2d");
ctx.canvas.width = size;
ctx.canvas.height = size;
const myPixels = [
[8, 5],
[6, 18],
[10, 10],
[15, 13, 2, 2, "fuchsia"], // [x, y, w, h, color]
];
// 1. Draw black background
drawRect(ctx, 0, 0, size, size, "#000");
// 2. Draw individual whites
myPixels.forEach(args => drawRect(ctx, ...args));canvas {
image-rendering: pixelated;
width: 10em;
}<canvas id="cvs"></canvas>
因此,通过使用上面的内容,您还可以使用[10, 10, 3, 3, "#fb0"]而不是[10, 10] (默认情况下是单个白色像素)创建一个较大的方形像素。
以上只是以下基本示例的功能方法:
const ctx = document.querySelector("#cvs").getContext("2d");
ctx.canvas.width = 20;
ctx.canvas.height = 20;
// 1. Color all black
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// 2. Color white pixels individually:
const myPixels = [
[8, 5],
[6, 18],
[10, 10],
[15, 13],
];
myPixels.forEach((args) => {
ctx.fillStyle = "#fff";
ctx.fillRect(args[0], args[1], 1, 1);
});canvas {
image-rendering: pixelated;
width: 10em;
}<canvas id="cvs"></canvas>
发布于 2022-10-07 21:56:10
下面是一个使用ImageData的实现,我们在随机位置绘制10个像素
const c = document.querySelector("#cvs")
const img = new ImageData(c.width, c.height)
const img_data = new Uint32Array(img.data.buffer)
var myPixels = []
for (var i=1; i<=10; i++)
myPixels.push({
x: Math.floor(Math.random() * c.width),
y: Math.floor(Math.random() * c.height)
})
myPixels.forEach((p) => img_data[p.y * c.width + p.x] = 68719411792)
c.getContext("2d").putImageData(img, 0, 0)canvas {
image-rendering: pixelated;
width: 10em;
}<canvas id="cvs" width=20 height=20></canvas>
https://stackoverflow.com/questions/73992017
复制相似问题