JS有现成的拖拽命令,但是只能实现简单的拖拽功能,下面演示的可以在画布的任意一个地方拖拽,并停留在画布的任意地方。
整个框架代码如下:
<html>
<head>
<meta charset="UTF-8">
<title>拖拽放置</title>
<link rel="stylesheet" href="mycss.css" type="text/css" />
</head>
<body>
<div id="myMenu">
<div>插入模块</div>
<div onclick="copycontent('source.png')"><img src="./Image/source.png"></div>
<div onclick="copycontent('Station.png')"><img src="./Image/Station.png"></div>
<div onclick="copycontent('Drain.png')"><img src="./Image/Drain.png"></div>
<div onclick="connectcontent()"><img src="./Image/Connector.png"></div>
</div>
<div id="container">
<div id="heading">顶部菜单栏</div>
<div id="content-body"></div>
<div id="footing">底部状态栏</div>
</div>
<script src="./myjs.js" type="text/javascript"></script>
<script>
//1.0 生成画笔
const canvas = document.createElement('canvas')
canvas.width =document.getElementById("content-body").clientWidth-4
canvas.height = document.getElementById("content-body").clientHeight-4
canvas.id = 'canvas'
document.getElementById("content-body").appendChild(canvas)
let ctx = canvas.getContext('2d') //画笔
//1.1 双缓存绘图,避免闪烁
const tempcanvas = document.createElement('canvas')
tempcanvas.width = document.getElementById("content-body").clientWidth-4
tempcanvas.height = document.getElementById("content-body").clientHeight-4
tempcanvas.id = 'tempcanvas'
let tempctx = tempcanvas.getContext('2d') //画笔
//1.2 鼠标按下监听
canvas.addEventListener('mousedown', e => {
saveInfo(e)
})
//1.3 鼠标移动
canvas.addEventListener('mousemove', e => {
DrawPicture(e)
})
//1.4 鼠标抬起事件
canvas.addEventListener('mouseup', e => {
canvasInfo.status = statusConfig.IDLE
canvas.style.cursor = ''
})
//1.5 鼠标离开事件
canvas.addEventListener('mouseleave', e => {
canvasInfo.status = statusConfig.IDLE
canvas.style.cursor = ''
})
</script>
</body>
</html>