# Canvas2D实现对图片进行网格变换

2020/06/12 20:04

①把图片水平垂直分成m×n份，每份沿对角线划分出两个三角形；

②移动图片四个顶点，对移动后的图像再进行一遍①操作；

③遍历每个三角形，通过三角形的变化计算出仿射变换矩阵，应用到原图，并裁剪出变化后的三角形区域；

① CanvasRenderingContext2D.transform()，用于对图像进行仿射变换；

② CanvasRenderingContext2D.clip()，用于裁剪仿射后的图像


let ctx = null
let imgWidth = 0
let imgHeight = 0
const CANVAS_WIDTH = 800
const CANVAS_HEIGHT = 800
let newPoints // 图片四个角的坐标
let originPoints // 图片四个角的原始坐标
const splitH = 10 // 图片分割成的行数
const splitV = 10 // 图片分割成的列数
let splitPoints = [] // 被分割出来的点的集合
let originSplitPoints // 被分割出来的点的原始集合

let imgUrl = 'https://kaysama.gitee.io/image-host/happy.jpg'
const matches = location.search.substring(1).match(/(^|&)img=([^&]*)(&|\$)/)
if (matches) {
imgUrl = decodeURI(matches[2])
}
let imgLeft, imgTop // 图片位置
const img = new Image()
img.src = imgUrl
const canvas = document.getElementById('canvas')
let pageWidth = window.innerWidth
let pageHeight = window.innerHeight
let canvasLeft = (pageWidth - CANVAS_WIDTH) / 2
let canvasTop = (pageHeight - CANVAS_HEIGHT) / 2
let targetPoint // 选中的圆
let mouseX, mouseY // 鼠标位置

ctx = canvas.getContext('2d')

canvas.width = CANVAS_WIDTH
canvas.height = CANVAS_HEIGHT

// 图片最宽最高不能超过canvas宽高的一半
imgWidth = img.width
imgHeight = img.height
const imgRatio = imgWidth / imgHeight
if (imgWidth > CANVAS_WIDTH / 2) {
imgWidth = CANVAS_WIDTH / 2
imgHeight = imgWidth / imgRatio
}
if (imgHeight > CANVAS_HEIGHT / 2) {
imgHeight = CANVAS_HEIGHT / 2
imgWidth = imgHeight * imgRatio
}
img.width = imgWidth
img.height = imgHeight

imgLeft = (canvas.width - imgWidth) / 2
imgTop = (canvas.height - imgHeight) / 2

originPoints = [
{
x: imgLeft, y: imgTop
},
{
x: imgLeft + imgWidth, y: imgTop
},
{
x: imgLeft + imgWidth, y: imgTop + imgHeight
},
{
x: imgLeft, y: imgTop + imgHeight
},
]

originSplitPoints = generatePoints(originPoints, splitH, splitV)

newPoints = JSON.parse(JSON.stringify(originPoints))

window.onresize = function () {
pageWidth = document.documentElement.clientWidth
pageHeight = document.documentElement.clientHeight
canvasLeft = (pageWidth - CANVAS_WIDTH) / 2
}
let dragging = false // 拖动中
document.body.onmousedown = function (e) {
dragging = true
mouseX = e.clientX - canvasLeft
mouseY = e.clientY - canvasTop
console.log(newPoints, e.clientY, mouseX, mouseY)
for (let i = 0; i < 4; i++) {
if (mouseX > newPoints[i].x - arcRadius && mouseX < newPoints[i].x + arcRadius && mouseY > newPoints[i].y - arcRadius && mouseY < newPoints[i].y + arcRadius) {
targetPoint = newPoints[i]
console.log('targetPoint:', targetPoint)
break
}
}
}
document.body.onmousemove = function (e) {
if (dragging && targetPoint) {
if (e.pageX - canvasLeft < 0) {
targetPoint.x = 0
}
else if (e.pageX - canvasLeft > CANVAS_WIDTH) {
targetPoint.x = CANVAS_WIDTH
}
else {
targetPoint.x = e.pageX - canvasLeft
}

if (e.pageY - canvasTop < 0) {
targetPoint.y = 0
}
else if (e.pageY - canvasTop > CANVAS_HEIGHT) {
targetPoint.y = CANVAS_HEIGHT
}
else {
targetPoint.y = e.pageY - canvasTop
}
update()
}
}
document.body.onmouseup = function (e) {
dragging = false
}

update()
}

function update () {

const newSplitPoints = generatePoints(newPoints, splitH, splitV)

ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
ctx.save()
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)

for (let i = 0; i < newSplitPoints.length; i++) {
if (i < newSplitPoints.length - splitH - 2 && (i + 1) % (splitH + 1) !== 0) {
drawTriangleImage(
originSplitPoints[i + 1], originSplitPoints[i + 1 + splitH + 1], originSplitPoints[i + splitH + 1],
newSplitPoints[i + 1], newSplitPoints[i + 1 + splitH + 1], newSplitPoints[i + splitH + 1]
) // 先画下三角
drawTriangleImage(
originSplitPoints[i], originSplitPoints[i + 1], originSplitPoints[i + splitH + 1],
newSplitPoints[i], newSplitPoints[i + 1], newSplitPoints[i + splitH + 1]
)  // 再画上三角
}
// 四个角
if (i === 0 || i === splitH || i === (splitH + 1) * splitV || i === (splitH + 1) * (splitV + 1) - 1) {
drawArc(newSplitPoints[i])
}
}
ctx.restore()
}

/**
* 生成分割点
* @param points 四边形四个点
* @param splitH “水平”方向被等分数
* @param splitV “竖直”方向被等分数
*/
function generatePoints (points, splitH, splitV) {
splitPoints = []
let vLeft = {
x: (points[3].x - points[0].x) / splitV,
y: (points[3].y - points[0].y) / splitV
}
let vRight = {
x: (points[2].x - points[1].x) / splitV,
y: (points[2].y - points[1].y) / splitV
}
let x1, y1, x2, y2
let i, j
for (i = 0; i <= splitV; i++) {
x1 = points[0].x + vLeft.x * i
y1 = points[0].y + vLeft.y * i
x2 = points[1].x + vRight.x * i
y2 = points[1].y + vRight.y * i
for (j = 0; j <= splitH; j++) {
splitPoints.push({
x: x1 + (x2 - x1) / splitH * j,
y: y1 + (y2 - y1) / splitH * j
})
}
}
return splitPoints
}

/**
* 画三角形图片
*/
function drawTriangleImage (p1, p2, p3, newP1, newP2, newP3) {
const matrixFrom = new Matrix(
// 使用列向量
[
p1.x, p1.y, 1,
p2.x, p2.y, 1,
p3.x, p3.y, 1,
],
3, // 3行（带齐次坐标 ）
3, // 3列
'column'
)
const matrixTo = new Matrix(
// 使用列向量
[
newP1.x, newP1.y, 1,
newP2.x, newP2.y, 1,
newP3.x, newP3.y, 1,
],
3, // 3行（带齐次坐标 ）
3, // 3列
'column'
)
const matrixTransform = matrixTo.multiply(matrixFrom.getInverseMatrix())
const itemList = matrixTransform.itemList
ctx.save()
//根据变换后的坐标创建剪切区域
ctx.beginPath()
ctx.moveTo(newP1.x, newP1.y)
ctx.lineTo(newP2.x, newP2.y)
ctx.lineTo(newP3.x, newP3.y)
ctx.closePath()
ctx.lineWidth = 1
ctx.strokeStyle = 'green'
ctx.stroke()
ctx.clip()
//绘制图片
ctx.transform(itemList[0][0], itemList[1][0], itemList[0][1], itemList[1][1], itemList[0][2], itemList[1][2])
ctx.drawImage(img, imgLeft, imgTop, imgWidth, imgHeight)
ctx.restore()
}

/**
* 画四边形的四个点
*/
function drawArc (point) {
ctx.save()
ctx.lineWidth = 2
ctx.beginPath()
ctx.arc(point.x, point.y, arcRadius, 0, 2 * Math.PI)
ctx.strokeStyle = 'red'
ctx.stroke()
ctx.restore()
}


5
6 收藏

05/31 18:22

1 评论
6 收藏
5