Skip to content

Commit

Permalink
Fixed anti aliasing issue
Browse files Browse the repository at this point in the history
  • Loading branch information
souravtecken committed Mar 31, 2020
1 parent 03c4090 commit d0efa63
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@

<canvas id="myCanvas" height="600px" width="800px" oncontextmenu="return false;">
Hello, World!
</canvas>
</canvas>

<script type="text/javascript" src="./js/index.js"></script>
</body>
Expand Down
8 changes: 6 additions & 2 deletions js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,15 @@ canvas.addEventListener("contextmenu", (event) => {
})

canvas.addEventListener("mousedown", (event) => {
Paint.drawPath(event.offsetX, event.offsetY);
if(event.buttons == 1){
Paint.movePoint(event.offsetX, event.offsetY);
Paint.drawPath(event.offsetX, event.offsetY);
}
})

canvas.addEventListener("mouseup", () => {
canvas.addEventListener("mouseup", (event) => {
Paint.startPath();
Paint.movePoint(event.offsetX, event.offsetY);
})

function initToolBox(){
Expand Down
26 changes: 25 additions & 1 deletion js/paint.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ class PaintJs {
this.ctx.closePath();
}

movePoint(x, y){
this.x = x;
this.y = y;
}

paintBucket(x, y, color){
const canvasHeight = this.canvas.clientHeight;
const canvasWidth = this.canvas.clientWidth;
Expand Down Expand Up @@ -90,14 +95,25 @@ class PaintJs {
this.ctx.fill();
}

drawLineNoAliasing(sx, sy, tx, ty) {
const dist = DBP(sx,sy,tx,ty);
const ang = getAngle(tx-sx,ty-sy);
for(let i=0;i < dist; ++i) {
this.ctx.fillRect(Math.round(sx + Math.cos(ang)*i - this.ctx.lineWidth/2),
Math.round(sy + Math.sin(ang)*i - this.ctx.lineWidth/2),
this.ctx.lineWidth,this.ctx.lineWidth);
}
}

drawPath(x, y) {
this.ctx.lineTo(x, y);
this.drawLineNoAliasing(this.x, this.y, x, y);
this.ctx.stroke();
this.ctx.beginPath();
this.drawPoint(x, y);
this.ctx.fill();
this.ctx.beginPath();
this.ctx.moveTo(x, y);
this.movePoint(x, y);
}
}

Expand All @@ -115,4 +131,12 @@ function hexToRGB(hex){
let G = parseInt(hex.substring(2,4), 16);
let B = parseInt(hex.substring(4,6), 16);
return [R, G, B, 255];
}

function DBP(x1,y1,x2,y2) {
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
// finds the angle of (x,y) on a plane from the origin
function getAngle(x, y) {
return Math.atan(y/(x==0?0.01:x))+(x<0?Math.PI:0);
}

0 comments on commit d0efa63

Please sign in to comment.