<html>
<head>
<script>
const RECT_SIZE = 20;
var
_canvas;
var
_context;
var
_list =
new
ShapeList;
var
_ismoving =
false
;
function
Rect() {
this
.isSelected =
false
;
this
.x = 0;
this
.y = 0;
this
.width = 1;
this
.height = 1;
}
Rect.prototype.contains =
function
(x,y){
var
right =
this
.x +
this
.width;
var
bottom =
this
.y +
this
.height;
return
x >
this
.x && x < right &&
y >
this
.y && y < bottom;
}
function
ShapeList(){
this
.items = [];
this
.selectedItem =
null
;
this
.offsetX = -1;
this
.offsetY = -1;
}
ShapeList.prototype.addItem =
function
(x,y,width,height){
var
rect =
new
Rect;
rect.x = x;
rect.y = y;
rect.width = width;
rect.height = height;
this
.items.push(rect);
}
ShapeList.prototype.selectAt =
function
(x,y){
if
(
this
.selectedItem)
this
.selectedItem.isSelected =
false
;
this
.selectedItem =
null
;
for
(
var
i = 0; i <
this
.items.length; i++) {
var
rect =
this
.items[i];
if
(rect.contains(x,y))
{
this
.selectedItem =
this
.items[i];
this
.offsetX = x -
this
.items[i].x;
this
.offsetY = y -
this
.items[i].y;
this
.items[i].isSelected =
true
;
break
;
}
}
}
function
canvas_mousedown(e){
var
x = e.pageX - _canvas.offsetLeft;
var
y = e.pageY - _canvas.offsetTop;
_list.selectAt(x,y)
if
(!_list.selectedItem)
_list.addItem(x-RECT_SIZE,y-RECT_SIZE,RECT_SIZE*2,RECT_SIZE*2);
_ismoving =
true
;
draw();
}
function
canvas_mousemove(e){
if
(_ismoving && _list.selectedItem){
var
x = e.pageX - _canvas.offsetLeft;
var
y = e.pageY - _canvas.offsetTop;
_list.selectedItem.x = x - _list.offsetX;
_list.selectedItem.y = y - _list.offsetY;
draw();
}
}
function
canvas_mouseup(e){
_ismoving =
false
;
}
function
clear(deleteData){
_context.clearRect(0,0,_canvas.width,_canvas.height);
if
(deleteData)
_list.items = [];
}
function
draw(){
clear();
for
(
var
i = _list.items.length-1;i>=0; i--) {
drawRect(_list.items[i]);
}
}
function
drawRect(rect){
_context.fillRect(rect.x,rect.y,rect.width,rect.height);
if
(rect.isSelected)
{
_context.save();
_context.strokeStyle =
"red"
;
_context.strokeRect(rect.x,rect.y,rect.width,rect.height);
_context.restore();
}
}
$(
function
(){
_canvas = document.getElementById(
"canvas"
);
_context = _canvas.getContext(
"2d"
);
_context.fillStyle =
"wheat"
;
_canvas.onmousedown = canvas_mousedown;
_canvas.onmousemove = canvas_mousemove;
_canvas.onmouseup = canvas_mouseup;
$(
"#button1"
).click(
function
(){
clear(
true
);
});
});
</script>
</head>
<body>
<div>
<button id=
"button1"
>Clear</button>
</div>
<canvas id=
"canvas"
width=
"400px"
height=
"400px"
style=
"border: 1px solid gray;"
></canvas>
</body>
</html>