<canvas id="ca">
您的浏览器不支持canvas,请更换浏览器!
</canvas>
实现拖动主要靠三个事件
mousemove,mousedown,mouseup
我们备注一个状态,canDrag,可拖动的意思,鼠标按下,可拖动为true,鼠标抬起,可拖动为false,当鼠标移动时,如果可拖动为true,就随鼠标移动,下面来看如何动
const ca = document.getElementById('ca')
const ctx = ca.getContext('2d')
const container = document.getElementsByClassName('canvas')[0]
const posit = ca.getBoundingClientRect()//获取canvas这个div到网页边缘的距离
container.addEventListener('mousedown', function(e) {
canDrag=true
this.startX = e.clientX - posit.left
this.startY = e.clientY - posit.top
})
container.addEventListener('mouseup', function(e) {
canDrag=false
})
我们用obj来存储一个图形的数据,如obj=[//0-形状类型 , 1-x ,2-y ,3-width, 4-height]
container.addEventListener('mousemove', function(e) {
obj[1] = e.clientX - posit.left - obj[3] / 2 //移动后的x坐标,-obj[3]/2表示坐标以中心点为基准
obj[2] = e.clientY - posit.top - obj[4] / 2 //同上,y坐标
draw(e.clientX - posit.left, e.clientY - posit.top)
})
draw函数中实现图形绘制
这里假设多个图形在shapeList中,obj为其中之一
注意reset()清空画布
function reset() {//清空画布
ca.width = ca.width
ca.height = ca.height
}
function draw(x = 9999, y = 0) {
reset()
let hover_type = 'none' //鼠标在哪种类型元素上none,img,border,link
let cursor = 'auto' //鼠标状态
ctx.font = "bold 13px Arial"; //画笔样式
let title = ''
ctx.beginPath()
ctx.rect(0, 0, ca.width, ca.height);
ctx.closePath()
if (ctx.isPointInPath(x, y)) {
cursor = 'auto'
title = ''
hover_type = 'none'
}
//清空状态
shapeList.forEach((item, i) => {
if (item[0] === 1) { //线
ctx.beginPath();
ctx.moveTo(item[1], item[2]);
ctx.lineTo(item[1] + item[3], item[2] + item[4]);
ctx.setLineDash([10, 10, 10]);
ctx.lineWidth = 5
ctx.closePath()
ctx.strokeStyle =“yellow”
ctx.stroke()
} else if (item[0] === 2) { //椭圆
ctx.beginPath()
ctx.setLineDash([10, 10, 10]);
ctx.strokeStyle = "yellow"
ctx.fillStyle = "pink"
ctx.ellipse(item[1] + item[3] / 2, item[2] + item[4] / 2, item[3] / 2, item[4] / 2, 0, 0, Math.PI * 2)
ctx.closePath()
ctx.fill()
ctx.stroke()
} else if (item[0] === 3) { //矩形
ctx.beginPath()
ctx.setLineDash([10, 10, 10]);
ctx.strokeStyle = “yellow”
ctx.rect(item[1], item[2], item[3], item[4]);
ctx.fillStyle = "pink"
// ctx.fillRect(item[1], item[2], item[3], item[4]);
ctx.closePath()
ctx.fill()
ctx.stroke()
}
if (ctx.isPointInPath(x, y)) {
hover_type = 'shape'
}
//isPointInxxxxx来判断鼠标当前是否在xx上
if (ctx.isPointInStroke(x, y)) {
cursor = 'crosshair'
title = '鼠标在边框上'
ctx.strokeStyle = "red"
ctx.stroke()
}
})
//这里有个状态,鼠标在边框上时,和鼠标在其它地方时,这里状态变化提示可连线等,连线将在其它文章中讲到
$(ca).css({
cursor: cursor,
})
//鼠标放在该图案上显示的提示文字
$(ca).attr({
title: title
})
}
思路大概是这样,代码在我的项目中提取出来的,可能有些不完善,后续会继续更新
canvas实现绘制拓扑图功能
--2021