JSFiddle - React, Tailwind, and code Playground
by garciaVvV
HTML
<canvas id="canvas" height="1000" width="1000"></canvas>
CSS
body{margin:0px;}
JavaScript
var canvas = document.getElementById("canvas");
var ctx=canvas.getContext("2d");
function aliasedCircle(ctx, xc, yc, r) { // NOTE: for fill only!
var x = r, y = 0, cd = 0;
// middle line
ctx.rect(xc - x, yc, r<<1, 1);
while (x > y) {
cd -= (--x) - (++y);
if (cd < 0) cd += x++;
ctx.rect(xc - y, yc - x, xc + y - (xc - y), 1); // upper 1/4
ctx.rect(xc - x, yc - y, x<<1, 1); // upper 2/4
ctx.rect(xc - x, yc + y, x<<1, 1); // lower 3/4
ctx.rect(xc - y, yc + x, xc + y - (xc - y), 1); // lower 4/4
}
}
/*generate coordinates of a bresenham line
and draw a circle at each coordinates*/
function lineXY(mouseX, mouseY, mouseXX, mouseYY){
var x0= mouseX;
var y0= mouseY;
var x1= mouseXX;
var y1= mouseYY;
var coordinatesArray = [];
// Translate coordinates
// Define differences and error check
var dx = Math.abs(x1 - x0);
var dy = Math.abs(y1 - y0);
var sx = (x0 < x1) ? 1 : -1;
var sy = (y0 < y1) ? 1 : -1;
var err = dx - dy;
// Set first coordinates
coordinatesArray.push([x0,y0]);
// Main loop
while (!((x0 == x1) && (y0 == y1))) {
var e2 = err << 1;
if (e2 > -dy) {
err -= dy;
x0 += sx;
}
if (e2 < dx) {
err += dx;
y0 += sy;
}
// Set coordinates
coordinatesArray.push([x0,y0]);
// Return the result
}
for(var i=0;i<coordinatesArray.length;i++) {
aliasedCircle(ctx, coordinatesArray[i][0], coordinatesArray[i][1], 100);
}
}
//draw on mouse down
function mouseDown(){
$(window).on("mousedown", function(e){
$(window).off("mousedown");
var mouseX=e.clientX;
var mouseY=e.clientY;
ctx.fillStyle="red";
ctx.beginPath();
aliasedCircle(ctx, mouseX, mouseY, 100);
ctx.fill();
ctx.closePath();
ctx.fillStyle="grey";
$(window).on("mousemove", function(e){
var mouseXX = e.clientX;
var mouseYY = e.clientY;
ctx.beginPath();
...