haohaio
努力学习,艰苦奋斗
写写代码,记记笔记
写了一个关于 Canvas 图形拖动变形的综合性 Demo,有兴趣的话可以看一下 canvas-drag
这里拖动变形是指拖动多边形的一个角来改变多变形的形状。
这里还是以正六边形为例,直接上代码。
<!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" /> <meta name ="viewport" content ="width=device-width, initial-scale=1.0" /> <title > Canvas 图形拖动</title > </head > <body > <canvas id ="canvas1" width ="600" height ="300" > </canvas > <script src ="./index.js" > </script > </body > </html >
const points = []for (let i = 0 ; i < 6 ; i++) { let point = { x: 150 + 50 * Math .cos((2 * Math .PI * i) / 6 ), y: 150 + 50 * Math .sin((2 * Math .PI * i) / 6 ), } points.push(point) } const canvas = document .getElementById('canvas1' )const ctx = canvas.getContext('2d' )paint() function paint ( ) { ctx.clearRect(0 , 0 , canvas.width, canvas.height) ctx.fillStyle = 'rgba(0, 0, 0, 0.2)' ctx.fillRect(0 , 0 , canvas.width, canvas.height) ctx.beginPath() points.forEach((point, index ) => { if (!index) { ctx.moveTo(point.x + 5 , point.y + 5 ) } else { ctx.lineTo(point.x + 5 , point.y + 5 ) } }) ctx.closePath() ctx.strokeStyle = '#1890FF' ctx.lineWidth = 2 ctx.stroke() ctx.fillStyle = '#D0E8FF' ctx.fill() ctx.strokeStyle = 'white' ctx.lineWidth = 2 points.forEach((point ) => { ctx.strokeRect(point.x, point.y, 10 , 10 ) }) } let isInRect = false let dragIndex = [] let lastDragIndex = null canvas.onmousemove = function (e ) { const x = e.offsetX const y = e.offsetY const point = checkBoundary(x, y) isInRect = isInSixRect(point) if (isInRect) { canvas.style.cursor = 'crosshair' } else { canvas.style.cursor = 'auto' } if (dragIndex.length) { if (lastDragIndex) { for (let i = 0 ; i < dragIndex.length; i++) { const index = dragIndex[i] if (index === lastDragIndex) { updatePoint(point, lastDragIndex) return } } } updatePoint(point, dragIndex[0 ]) } } function checkBoundary (x, y ) { if (x <= 2 ) { x = 2 } if (x >= canvas.width - 12 ) { x = canvas.width - 12 } if (y <= 2 ) { y = 2 } if (y >= canvas.height - 12 ) { y = canvas.height - 12 } return { x, y } } function isInSixRect (mousePoint, isMouseDownEvent = false ) { let flag = false points.forEach((point, index ) => { if ( mousePoint.x >= point.x - 2 && mousePoint.x <= point.x + 12 && mousePoint.y >= point.y - 2 && mousePoint.y <= point.y + 12 ) { if (isMouseDownEvent) { dragIndex.push(index) } flag = true } }) return flag } canvas.onmousedown = function (e ) { const point = { x: e.offsetX, y: e.offsetY, } isInSixRect(point, true ) } function updatePoint (point, index ) { lastDragIndex = index points[index].x = point.x points[index].y = point.y paint() } document .onmouseup = function (e ) { dragIndex = [] }
OK,Canvas 图形拖动变形到这里也可以了~
本文代表个人观点,内容仅供参考。若有不恰当之处,望不吝赐教!
Please enable JavaScript to view the comments powered by
Disqus.