<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Beijing-Hong</title>
<style>
canvas {
border: 1px solid black
}
</style>
</head>
<body>
</body>
<script>
const canvas = ('canvas')
= 400
= 400
= 'canvas'
(canvas)
let ctx = ('2d') //brushes
// status flag
const statusConfig = {
IDLE: 0, //
DRAGSTART: 1, //Mouse over
DRAGGING: 2 //attacking and dragging
}
// Canvas Information
const canvasInfo = {
status: , //state of affairs
dragTarget: null, //drag-and-drop (computing)
lastEvtPos: { //Previous position
x: null,
y: null
},
offsetEvtPos: { //Previous Offset
x: null,
y: null
}
}
let circles = [] //Stored Drawn Circles
// draw a circle
const drawCircle = (ctx, cx, cy, r) => {
()
() //Start drawing.
(cx, cy, r, 0, * 2)
= 'pink'
= 'pink'
() //Stroke Mode
()
() //close
()
}
drawCircle(ctx, 100, 100, 10)
// Store the position of the circle
({
x: 100,
y: 100,
r: 10
})
drawCircle(ctx, 200, 150, 20)
({
x: 200,
y: 150,
r: 20
})
// Element Drag and Drop Canvas coordinates for mouse
const getCanvasPostion = e => {
return {
x: , //The position of the mouse in the page while subtracting the offset of the canvas element itself
y: ,
}
}
// Distance between two points
const getInstance = (p1, p2) => {
// The exponentiation operators **, which self-multiply ( - ) and ( - ), respectively.
return (( - ) ** 2 + ( - ) ** 2)
// or
// function, which is used to calculate the specified power of a specified number.
// return ((( - ), 2) + (( - ), 2))
}
// Determine if the mouse is inside a circle
const ifInCirlce = (pos) => {
for (let i = 0; i < ; i++) {
if (getInstance(circles[i], pos) < circles[i].r) {
return circles[i]
}
}
return false
}
// Mouse click listener
('mousedown', e => {
const canvasPostion = getCanvasPostion(e)
const circleRef = ifInCirlce(canvasPostion)
if (circleRef) {
(circleRef);
= circleRef //drag-and-drop (computing)
=
= canvasPostion
= canvasPostion
}
})
// Mouse over
('mousemove', e => {
const canvasPostion = getCanvasPostion(e)
const {dragTarget} = canvasInfo
if (ifInCirlce(canvasPostion)) {
= 'all-scroll'
}else {
= ''
}
if (!dragTarget) return
if ( === && getInstance(canvasPostion, ) > 5) {
('try to drag');
=
= canvasPostion
}else if( === ){
('draging');
+= ( - )
+= ( - ) //Offset-based
(0,0, , ) //Empty Canvas
(c => drawCircle(ctx, , , ))
= canvasPostion
}
})
('mouseup', e => {
=
})
('mouseleave', e => {
=
= ''
})
</script>
</html>