dps_canvas
Version:
Html canvas üzerinde şekiller oluşturmanızı sağlar
119 lines (93 loc) • 3.06 kB
JavaScript
import Base from "./parent";
import Text from "./text";
import { uniqueId } from "./utils/helper";
import { showInput } from "./utils/showInput";
export default class Square {
/**
* @private
*/
static #squares = [];
static activeSquare = []
static draw({ x, y, width, height, color, stroke, dash }) {
Base.context.beginPath();
Base.context.fillStyle = color || Base.squareColor;
Base.context.strokeStyle = color || Base.squareColor
dash && Base.context.setLineDash([15, 3, 3, 3]);
Base.context.rect(x, y, width, height ? height : width);
stroke ? Base.context.stroke() : Base.context.fill();
Base.context.closePath();
}
static get data() {
return Square.#squares
}
static get lastItem() {
return Square.data[Square.data.length - 1]
}
static add(arg) {
let { x, y, width, height, name } = arg
const uid = uniqueId()
if (width < 0) {
width = Math.abs(width)
x = x - width
}
if (height < 0) {
height = Math.abs(height)
y = y - height
}
/**
* if width or height is not valid
*/
if (width < Base.minDimensionsSquare || height < Base.minDimensionsSquare) {
return console.info(`Width yada height değeri ${Base.minDimensionsSquare} değerinden büyük olmalı`)
}
Square.#squares.push({ ...arg, width, height, x, y, uid, type: "square" })
Text.add({ uid, name, x: x + width / 2, y: y + (height || width) / 2 });
if(!name) {
Base.setActiveShape(Square.data[Square.data.length - 1])
Base.isShowInput = true
showInput({ square: Square.lastItem, text: Text.lastItem })
}
}
static handleDown(x, y) {
const item = this.prototype.getCollisionElement(x, y)
if (!item.square && !item.text) {
Base.isMoving = false
return
}
Base.isMoving = true
return item
}
static handleContextmenu(x, y) {
return this.prototype.getCollisionElement(x, y).square
}
static handleDblClick(x, y) {
const { square, text } = this.prototype.getCollisionElement(x, y)
if (!square) {
return Base.isShowInput = false
}
Base.isShowInput = true
return { square, text }
}
static clearItem() {
Square.#squares = []
}
/**
* Delete shape and text
*/
static delete(value) {
const indexSquare = Square.#squares.findIndex(sq => sq.uid === value?.uid)
const item = Square.#squares.splice(indexSquare, 1)
Text.deleteTextById(item[0]?.uid)
}
getCollisionElement(x, y) {
const square = Square.#squares.find(item => this.collisionDetection(x, y, { ...item }))
const text = Text.text.find(c => square?.uid === c?.uid)
return { square, text }
}
collisionDetection(cx, cy, target) {
return cx + 0 >= target.x &&
cx <= target.x + Math.abs(target.width) &&
cy + 0 >= target.y &&
cy <= target.y + (Math.abs(target.height) || Math.abs(target.width))
}
}