绘制Circle Jimp JavaScript [英] Draw Circle Jimp JavaScript

查看:130
本文介绍了绘制Circle Jimp JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用



问题是,当您放大时,它看起来真是断断续续。





如何使圆圈更平滑且不那么起伏?

解决方案

您需要创建 anti-aliasing 。通过简单地根据每个像素到中心的浮动距离来控制每个像素的灰度等级,即可轻松实现黑白效果。



例如,一个像素您的设置中250的距离应为黑色,而250.5的距离应为灰色(〜#808080)。
因此,您要做的就是考虑这些浮点数。



以下是使用Canvas2D API的示例,但核心逻辑直接适用于您的代码。



  const size = 500; const rad = size / 2; const black = 0xFF000000; // [0,0,0,255]; const white = 0xFFFFFFFF; // [255,255,255,255]; const img = new ImageData(size,size); const data = new Uint32Array(img.data.buffer); for(let x = 0; x< size; x ++) {for(let y = 0; y  

 <画布ID = c width = 500 height = 500>< / canvas>  


I'm trying to draw a circle in JavaScript with Jimp using the code below.

const Jimp = require("jimp");

const size = 500;
const black = [0, 0, 0, 255];
const white = [255, 255, 255, 255];
new Jimp(size, size, (err, image) => {
    for (let x = 0; x < size; x++) {
        for (let y = 0; y < size; y++) {
            const colorToUse = distanceFromCenter(size, x, y) > size / 2 ? black : white;
            const color = Jimp.rgbaToInt(...colorToUse);
            image.setPixelColor(color, x, y);
        }
    }
    image.write("circle.png");
});

It produces this.

Problem is, when you zoom in, it looks really choppy.

How can I make the circle smoother and less choppy?

解决方案

You need to create anti-aliasing. This is easily done for black and white by simply controlling the level of gray of each pixel based on the floating distance it has to the center.

E.g, a pixel with a distance of 250 in your setup should be black, but one with a distance of 250.5 should be gray (~ #808080). So all you have to do, is to take into account these floating points.

Here is an example using the Canvas2D API, but the core logic is directly applicable to your code.

const size = 500;
const rad = size / 2;
const black = 0xFF000000; //[0, 0, 0, 255];
const white = 0xFFFFFFFF; //[255, 255, 255, 255];

const img = new ImageData(size, size);
const data = new Uint32Array(img.data.buffer);

for (let x = 0; x < size; x++) {
  for (let y = 0; y < size; y++) {
    const dist = distanceFromCenter(rad, x, y);
    let color;
    if (dist >= rad + 1) color = black;
    else if (dist <= rad) color = white;
    else {
      const mult = (255 - Math.floor((dist - rad) * 255)).toString(16).padStart(2, 0);
      color = '0xff' + mult.repeat(3); // grayscale 0xffnnnnnn
    }
    // image.setPixelColor(color, x, y);
    data[(y * size) + x] = Number(color);
  }
}
//image.write("circle.png");
c.getContext('2d').putImageData(img, 0, 0);


function distanceFromCenter(rad, x, y) {
  return Math.hypot(rad - x, rad - y);
}

<canvas id="c" width="500" height="500"></canvas>

这篇关于绘制Circle Jimp JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆