Draw Circle Jimp JavaScript - javascript

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>

I'm sorry to says this but the answer is that you can't really do it. The problem is that a pixel is the minimal unit that can be drawn and you have to either draw it or not. So as long as you use some raster image format (as opposed to vector graphics) you can't draw a smooth line at a big zoom.
If you think about it, you might blame the problem onto the zooming app that doesn't know about the logic of the image (circle) and maps each pixel to many whole pixels. To put it otherwise, your image has only 500x500 pixels of information. You can't reliably build 5,000x5,000 pixels of information (which is effectively what 10x zooming is) from that because there is not enough information in the original image. So you (or whoever does the zooming) have to guess how to fill the missing information and this "chopping" is a result of the simplest (and the most widely used) guessing algorithm there is: just map every pixel on NxN pixels where N is zoom factor.
There are three possible workarounds:
Draw a much bigger image so you don't need to zoom it in the first place (but it will take much more space everywhere)
Use some vector graphics like SVG (but you'll have to change the library, and it might be not what you want in the end because there are some other problems with that)
Try to use anti-aliasing which is a clever trick used to subvert how humans see: you draw some pixels around the edge as some gray instead of black-and-white. It will look better at small zooms but at big enough zooms you'll still see the actual details and the magic will stop working.

Related

How to make the background change color smoothly in rainbow style?

I'm using P5.js library and I want to make the background of the canvas change color in rainbow style smoothly and continuously.
How can I do this? Thanks a lot in advance
Something like this
You could use the HSB colorMode. This allows you to basically "cycle" through the color wheel by using numbers from 0 to 360 (ie specify a degree on the color wheel). Using this idea, you can draw many rectangles on your canvas, spanning from the top of the canvas to the bottom (amount of rectangle specified by inc). Each rectangle will have a particular color.
Thus, joining all these rectangles will allow you to create a gradient-like effect.
By continuously providing an offset to your color (and restricting it within the bounds or 0 to 360) you can cycle through the color wheel.
See code below:
function setup() {
createCanvas(400, 400);
}
let cOffset = 0;
function draw() {
const inc = height/100;
colorMode(HSB);
for(let y = 0; y < height; y += inc) {
let h = y / height * 360;
fill(abs(h-cOffset)%360, 100, 100);
noStroke();
rect(0, y-inc, width, y);
}
cOffset += 5;
}
See working version here:
https://editor.p5js.org/NickParsons/sketches/1xfjY-ZoE

Rendering lots of sprites with hexagon shape from image using pixijs

I'm trying to create a hexagonal map with the list of terrain types.
At the moment I have the map that is drawn from the sprites that uses as a base texture the graphics with the shape of a hexagon.
I need to put a different images on them, but can't find a solution how to do it.
Here's the demo of what I have: https://codepen.io/cuddlemeister/pen/rPvwZw
I've tryied to do it in this way:
const texture = PIXI.Texture.fromImage(img);
const s = new PIXI.Sprite(texture);
s.mask = graphics;
But I get only one hexagon that mask being applyied to. And if I put graphics in a loop, I get performance issues.
Maybe I should just cut the images to get hexagons and simply draw sprites made from these images?
Here's what I want to achieve: http://i.imgur.com/xXLTK.jpg
Basically, I need to replace that white hexagons with some textures. How can I get this?
how about that:
https://jsfiddle.net/vxt5eqk4/
for each tile you use a clipmask
var scale = 8;
for (y = 0; y < 10; y++) {
for (x = 0; x < 10; x++) {
var offsetx = (y%2)*5 + x*10 - 6;
var offsety = y * 9 -3;
ctx.save();
ctx.beginPath();
ctx.moveTo(scale*(offsetx+5),scale*(offsety));
ctx.lineTo(scale*(offsetx+10),scale*(offsety+3));
ctx.lineTo(scale*(offsetx+10),scale*(offsety+9));
ctx.lineTo(scale*(offsetx+5),scale*(offsety+12));
ctx.lineTo(scale*offsetx,scale*(offsety+9));
ctx.lineTo(scale*offsetx,scale*(offsety+3));
ctx.closePath();
ctx.clip();
if((y%2 !== 0 || x%2 !== 0) && (y%2 === 0 || x%2 === 0)){
ctx.drawImage(img, scale*offsetx, scale*offsety, 10*scale, 12*scale);
}else{
ctx.drawImage(img2, scale*offsetx, scale*offsety, 10*scale, 12*scale);
}
ctx.restore();
}
a 10x12 grid seemed fine to me to draw a hexagon
the fiddle just shows a basic method to draw hexagonal tiles, the if part should be replaced by getting the proper image for the tile in the tilemap, should you use one

JavaScript Canvas how to stroke special text [duplicate]

I'm drawing an image onto a canvas using drawImage. It's a PNG that is surrounded by transparent pixels, like this:
How can I add a solid-colored border to the visible part of that image on the canvas? To clarify: I don't want a rectangle that surrounds the image's bounding box. The border should go around the grass patch.
I did consider using shadows, but I don't really want a glowing border, I want a solid one.
A bit late, but just draw the image offset which is much faster than analyzing the edges:
var ctx = canvas.getContext('2d'),
img = new Image;
img.onload = draw;
img.src = "http://i.stack.imgur.com/UFBxY.png";
function draw() {
var dArr = [-1,-1, 0,-1, 1,-1, -1,0, 1,0, -1,1, 0,1, 1,1], // offset array
s = 2, // thickness scale
i = 0, // iterator
x = 5, // final position
y = 5;
// draw images at offsets from the array scaled by s
for(; i < dArr.length; i += 2)
ctx.drawImage(img, x + dArr[i]*s, y + dArr[i+1]*s);
// fill with color
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = "red";
ctx.fillRect(0,0,canvas.width, canvas.height);
// draw original image in normal mode
ctx.globalCompositeOperation = "source-over";
ctx.drawImage(img, x, y);
}
<canvas id=canvas width=500 height=500></canvas>
==> ==>
First, attributions:
As #Philipp says, you'll need to analyze pixel data to get your outline border.
You can use the "Marching Squares" algorithm to determine which transparent pixels border the non-transparent grass pixels. You can read more about the Marching Squares algorithm here: http://en.wikipedia.org/wiki/Marching_squares
Michael Bostock has a very nice plugin version of Marching Squares in his d3 data visualization application (IMHO, d3 is the best open-source data visualization program available). Here's a link to the plugin: https://github.com/d3/d3-plugins/tree/master/geom/contour
You can outline the border of your grass image like this:
Draw your image on the canvas
Grab the image's pixel data using .getImageData
Configure the plug-in to look for transparent pixels bordering opaque pixels
// This is used by the marching ants algorithm
// to determine the outline of the non-transparent
// pixels on the image using pixel data
var defineNonTransparent=function(x,y){
var a=data[(y*cw+x)*4+3];
return(a>20);
}
Call the plugin which returns a set of points which outline the border of your image.
// call the marching ants algorithm
// to get the outline path of the image
// (outline=outside path of transparent pixels
points=geom.contour(defineNonTransparent);
Use the set of points to draw a path around your image.
Here's annotated code and a Demo:
// Marching Squares Edge Detection
// this is a "marching ants" algorithm used to calc the outline path
(function() {
// d3-plugin for calculating outline paths
// License: https://github.com/d3/d3-plugins/blob/master/LICENSE
//
// Copyright (c) 2012-2014, Michael Bostock
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//* Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//* Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//* The name Michael Bostock may not be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
geom = {};
geom.contour = function(grid, start) {
var s = start || d3_geom_contourStart(grid), // starting point
c = [], // contour polygon
x = s[0], // current x position
y = s[1], // current y position
dx = 0, // next x direction
dy = 0, // next y direction
pdx = NaN, // previous x direction
pdy = NaN, // previous y direction
i = 0;
do {
// determine marching squares index
i = 0;
if (grid(x-1, y-1)) i += 1;
if (grid(x, y-1)) i += 2;
if (grid(x-1, y )) i += 4;
if (grid(x, y )) i += 8;
// determine next direction
if (i === 6) {
dx = pdy === -1 ? -1 : 1;
dy = 0;
} else if (i === 9) {
dx = 0;
dy = pdx === 1 ? -1 : 1;
} else {
dx = d3_geom_contourDx[i];
dy = d3_geom_contourDy[i];
}
// update contour polygon
if (dx != pdx && dy != pdy) {
c.push([x, y]);
pdx = dx;
pdy = dy;
}
x += dx;
y += dy;
} while (s[0] != x || s[1] != y);
return c;
};
// lookup tables for marching directions
var d3_geom_contourDx = [1, 0, 1, 1,-1, 0,-1, 1,0, 0,0,0,-1, 0,-1,NaN],
d3_geom_contourDy = [0,-1, 0, 0, 0,-1, 0, 0,1,-1,1,1, 0,-1, 0,NaN];
function d3_geom_contourStart(grid) {
var x = 0,
y = 0;
// search for a starting point; begin at origin
// and proceed along outward-expanding diagonals
while (true) {
if (grid(x,y)) {
return [x,y];
}
if (x === 0) {
x = y + 1;
y = 0;
} else {
x = x - 1;
y = y + 1;
}
}
}
})();
//////////////////////////////////////////
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// checkbox to show/hide the original image
var $showImage=$("#showImage");
$showImage.prop('checked', true);
// checkbox to show/hide the path outline
var $showOutline=$("#showOutline");
$showOutline.prop('checked', true);
// an array of points that defines the outline path
var points;
// pixel data of this image for the defineNonTransparent
// function to use
var imgData,data;
// This is used by the marching ants algorithm
// to determine the outline of the non-transparent
// pixels on the image
var defineNonTransparent=function(x,y){
var a=data[(y*cw+x)*4+3];
return(a>20);
}
// load the image
var img=new Image();
img.crossOrigin="anonymous";
img.onload=function(){
// draw the image
// (this time to grab the image's pixel data
ctx.drawImage(img,canvas.width/2-img.width/2,canvas.height/2-img.height/2);
// grab the image's pixel data
imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
data=imgData.data;
// call the marching ants algorithm
// to get the outline path of the image
// (outline=outside path of transparent pixels
points=geom.contour(defineNonTransparent);
ctx.strokeStyle="red";
ctx.lineWidth=2;
$showImage.change(function(){ redraw(); });
$showOutline.change(function(){ redraw(); });
redraw();
}
img.src="http://i.imgur.com/QcxIJxa.png";
// redraw the canvas
// user determines if original-image or outline path or both are visible
function redraw(){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw the image
if($showImage.is(':checked')){
ctx.drawImage(img,canvas.width/2-img.width/2,canvas.height/2-img.height/2);
}
// draw the path (consisting of connected points)
if($showOutline.is(':checked')){
// draw outline path
ctx.beginPath();
ctx.moveTo(points[0][0],points[0][4]);
for(var i=1;i<points.length;i++){
var point=points[i];
ctx.lineTo(point[0],point[1]);
}
ctx.closePath();
ctx.stroke();
}
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" id="showImage" />Show Image<br>
<input type="checkbox" id="showOutline" />Show Outline Path<br>
<canvas id="canvas" width=300 height=450></canvas>
I was looking for a way to do this and it seems there are only laborious solutions.
I came up with a little workaround using shadows and a loop to display them all around the image:
// Shadow color and blur
// To get a blurry effect use rgba() with a low opacity as it will be overlaid
context.shadowColor = "red";
context.shadowBlur = 0;
// X offset loop
for(var x = -2; x <= 2; x++){
// Y offset loop
for(var y = -2; y <= 2; y++){
// Set shadow offset
context.shadowOffsetX = x;
context.shadowOffsetY = y;
// Draw image with shadow
context.drawImage(img, left, top, width, height);
}
}

JS canvas white lines when scaling

Using JavaScript I am displaying an array on an html 5 canvas. The program uses c.fillRect() for each value in the array. Everything looks normal until I scale it using c.scale(). After being scaled white lines are visible between the squares. I do know their white because that is the color of the background (When the background changes their color changes too).
Since the squares are 5 units apart I tried setting their width to 5.5 instead of 5; this only remove the white lines when zoom in far enough, but when zooming out the white lines were still there.
This is my code (unnecessary parts removed):
function loop()
{
c.resetTransform();
c.fillStyle = "white";
c.fillRect(0, 0, c.canvas.width, c.canvas.height);
c.scale(scale, scale);
c.translate(xViewportOffset, yViewportOffset);
...
for(var x = 0; x < array.length; x++)
{
for(var y = 0; y < array[x].length; y++)
{
...
c.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
c.fillRect(0 + x * 5, 200 + y * 5, 5, 5);
}
}
...
}
No scaling:
Zoomed in:
Zoomed out:
(the pattern changes depending on the amount of zoom)
Thanks for any help and if any other information is needed please let me know.
Update:
I am using Google Chrome
Version 71.0.3578.98 (Official Build) (64-bit)
This is probably because you are using non-integer values to set the context's scale and/or translate.
Doing so, your rects are not on pixel boundaries anymore but on floating values.
Let's make a simple example:
Two pixels, one at coords (x,y) (11,10) the other at coords (12,10).
At default scale, both pixels should be neighbors.
Now, if we apply a scale of 1.3, the real pixel-coords of the first square will be at (14.3,13) and the ones of the second one at (15.6,13).
None of these coords can hold a single pixel, so browsers will apply antialiasing, which consist in smoothing your color with the background color to give the impression of smaller pixels. This is what makes your grids.
const ctx = small.getContext('2d');
ctx.scale(1.3, 1.3);
ctx.fillRect(2,10,10,10);
ctx.fillRect(12,10,10,10);
const mag = magnifier.getContext('2d');
mag.scale(10,10);
mag.imageSmoothingEnabled = false;
mag.drawImage(small, 0,-10);
/* it is actually transparent, not just more white */
body:hover{background:yellow}
<canvas id="small" width="50" height="50"></canvas><br>
<canvas id="magnifier" width="300" height="300"></canvas>
To avoid this, several solutions, all dependent on what you are doing exactly.
In your case, it seems you'd win a lot by working on an ImageData which would allow you to replace all these fillRect calls to simpler and faster pixel manipulation.
By using a small ImageData, the size of your matrix, you can replace each rect to a single pixel. Then you just need to put this matrix on your canvas and redraw the canvas over itself at the correct scale after disabling the imageSmootingEnabled flag, which allows us to disable antialiasing for drawImage and CanvasPatterns only.
// the original matrix will be 20x20 squares
const width = 20;
const height = 20;
const ctx = canvas.getContext('2d');
// create an ImageData the size of our matrix
const img = ctx.createImageData(width, height);
// wrap it inside an Uint32Array so that we can work on it faster
const pixels = new Uint32Array(img.data.buffer);
// we could have worked directly with the Uint8 version
// but our loop would have needed to iterate 4 pixels every time
// just to draw a radial-gradient
const rad = width / 2;
// iterate over every pixels
for(let x=0; x<width; x++) {
for(let y=0; y<height; y++) {
// make a radial-gradient
const dist = Math.min(Math.hypot(rad - x, rad - y), rad);
const color = 0xFF * ((rad - dist) / rad) + 0xFF000000;
pixels[(y * width) + x] = color;
}
}
// here we are still at 50x50 pixels
ctx.putImageData(img, 0, 0);
// in case we had transparency, this composite mode will ensure
// that only what we draw after is kept on the canvas
ctx.globalCompositeOperation = "copy";
// remove anti-aliasing for drawImage
ctx.imageSmoothingEnabled = false;
// make it bigger
ctx.scale(30,30);
// draw the canvas over itself
ctx.drawImage(canvas, 0,0);
// In case we draw again, reset all to defaults
ctx.setTransform(1,0,0,1,0,0);
ctx.globalCompositeOperation = "source-over";
body:hover{background:yellow}
<canvas id="canvas" width="600" height="600"></canvas>

How can I get undistorted 2D Perlin noise as an image in p5.js?

I'm trying to draw a Perlin noise image in p5.js. I followed Daniel Shiffman's tutorials and he gives an example about how to set up 2D Perlin noise here (for convenience I have loaded this into this JSFiddle sketch).
Now I don't need the entire canvas filled with Perlin noise, but I just need a (smaller) image of perlin noise that I can use like an image file in the canvas. So, in the setup function I used createImage() and then the exact same algorithm to load the Perlin noise into the image. However, when I display this now, the noise looks totally distorted.
Here is my code:
// noise code originally by
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Code for: https://youtu.be/ikwNrFvnL3g
var inc = 0.01;
var noiseImg;
function setup() {
createCanvas(640, 360);
pixelDensity(1);
background("red");
var yoff = 0;
noiseImg = createImage(200, 200);
noiseImg.loadPixels();
for (var y = 0; y < height; y++) {
var xoff = 0;
for (var x = 0; x < width; x++) {
var index = (x + y * width) * 4;
var r = noise(xoff, yoff) * 255;
noiseImg.pixels[index + 0] = r;
noiseImg.pixels[index + 1] = r;
noiseImg.pixels[index + 2] = r;
noiseImg.pixels[index + 3] = 255;
xoff += inc;
}
yoff += inc;
}
noiseImg.updatePixels();
}
function draw() {
image(noiseImg, 0, 0);
}
JSFiddle
Does anyone know, why it is distorted although the noise algorithm hasn't changed and what I can do about it?
Thanks!
The width and height variables are for the overall campus, in your case 640 and 360 respectively. You use these variables to loop over every pixel in that space, but then you're setting the pixel array of an image that's only 200 by 200 pixels. (Or in your JSFiddle, 300 by 300 pixels.)
That's what's causing the distortion: you're drawing a 640x360 drawing of Perlin noise to a 200x200 image. This is resulting in some undefined behavior, which manifests as the distortion you're seeing.
To fix the problem, just loop over the bounds of the image, not the sketch itself.

Categories