pixel-editor/js/_drawLine.js

56 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-03-27 02:20:54 +03:00
//draw a line between two points on canvas
2020-04-04 10:41:56 +03:00
function line(x0, y0, x1, y1, brushSize) {
2019-03-27 02:20:54 +03:00
2020-04-04 10:41:56 +03:00
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;
while (true) {
//set pixel
// If the current tool is the brush
if (currentTool == 'pencil' || currentTool == 'rectangle') {
// I fill the rect
currentLayer.context.fillRect(x0-Math.floor(brushSize/2), y0-Math.floor(brushSize/2), brushSize, brushSize);
} else if (currentTool == 'eraser') {
// In case I'm using the eraser I must clear the rect
currentLayer.context.clearRect(x0-Math.floor(eraserSize/2), y0-Math.floor(eraserSize/2), eraserSize, eraserSize);
2020-04-04 10:41:56 +03:00
}
//if we've reached the end goal, exit the loop
if ((x0==x1) && (y0==y1)) break;
var e2 = 2*err;
if (e2 >-dy) {err -=dy; x0+=sx;}
if (e2 < dx) {err +=dx; y0+=sy;}
}
2020-03-15 18:32:48 +03:00
}
2020-04-04 10:41:56 +03:00
// draw a line between two points on canvas
function lineOnLayer(x0, y0, x1, y1, brushSize, context) {
2020-03-15 18:32:48 +03:00
2020-04-04 10:41:56 +03:00
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;
while (true) {
//set pixel
// If the current tool is the brush
if (currentTool == 'pencil' || currentTool == 'rectangle') {
// I fill the rect
context.fillRect(x0-Math.floor(brushSize/2), y0-Math.floor(brushSize/2), brushSize, brushSize);
} else if (currentTool == 'eraser') {
// In case I'm using the eraser I must clear the rect
2020-03-15 18:32:48 +03:00
context.clearRect(x0-Math.floor(eraserSize/2), y0-Math.floor(eraserSize/2), eraserSize, eraserSize);
2020-04-04 10:41:56 +03:00
}
// if we've reached the end goal, exit the loop
if ((x0==x1) && (y0==y1)) break;
var e2 = 2*err;
if (e2 >-dy) {err -=dy; x0+=sx;}
if (e2 < dx) {err +=dx; y0+=sy;}
}
}