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-4canvas.height = document.getElementById("content-body").clientHeight-4canvas.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-4tempcanvas.height = document.getElementById("content-body").clientHeight-4tempcanvas.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.IDLEcanvas.style.cursor = ''})//1.5 鼠标离开事件canvas.addEventListener('mouseleave', e => {canvasInfo.status = statusConfig.IDLEcanvas.style.cursor = ''})</script>
</body>
</html>