canvas实现图片马赛克的示例代码

2020-04-21 08:08:09易采站长站整理

self.canvas.addEventListener('mousedown', e => {
beginX = e.offsetX
beginY = e.offsetY
self.canvas.addEventListener('mouseup', e => {
endX = e.offsetX
endY = e.offsetY
if (self.isMasic) {
self.makeGrid(beginX, beginY, endX - beginX, endY - beginY)
return
}
if (self.isTailor) {
self.context.drawImage(Img, beginX, beginY, endX - beginX, endY - beginY, 0, 0, endX - beginX, endY - beginY)
return
}
})
})
}
},
drawRect (x, y, width, height, fillStyle, lineWidth, strokeStyle, globalAlpha) {
this.context.beginPath()
this.context.rect(x, y, width, height)
this.context.lineWidth = lineWidth
this.context.strokeStyle = strokeStyle
fillStyle && (this.context.fillStyle = fillStyle)
globalAlpha && (this.context.globalAlpha = globalAlpha)

this.context.fill()
this.context.stroke()
},
// 打马赛克
mosaic () {
let self = this
this.resetClickStatus()
this.isMasic = true
},
makeGrid (beginX, beginY, rectWidth, rectHight) {
const row = Math.round(rectWidth / this.squareEdgeLength) + 1
const column = Math.round(rectHight / this.squareEdgeLength) + 1
for (let i = 0; i < row * column; i++) {
let x = (i % row) * this.squareEdgeLength + beginX
let y = parseInt(i / row) * this.squareEdgeLength + beginY
this.setColor(x, y)
}
},
setColor (x, y) {
const imgData = this.context.getImageData(x, y, this.squareEdgeLength, this.squareEdgeLength).data
let r = 0, g = 0, b = 0
console.log(this.context.getImageData(x, y, this.squareEdgeLength, this.squareEdgeLength), JSON.stringify(imgData))
for (let i = 0; i < imgData.length; i += 4) {
r += imgData[i]g += imgData[i + 1]b += imgData[i + 2]}
r = Math.round(r / (imgData.length / 4))
g = Math.round(g / (imgData.length / 4))
b = Math.round(b / (imgData.length / 4))
this.drawRect(x, y, this.squareEdgeLength, this.squareEdgeLength, `rgb(${r}, ${g}, ${b})`, 2, `rgb(${r}, ${g}, ${b})`)
},
// 添加文字
addText () {
this.resetClickStatus()
this.isText = true
console.log('添加文字')
},
// 裁剪
tailor () {
this.resetClickStatus()
this.isTailor = true
console.log('裁剪')
} ,
// 旋转
rotate () {
// if (this.angle === 360) {
// this.angle = 90
// } else {
// this.angle += 90
// }
// if ([90, 270].includes(this.angle)) {
// this.canvas.setAttribute('width', this.image.height)
// this.canvas.setAttribute('height', this.image.width)
// } else {
// this.canvas.setAttribute('width', this.image.width)
// this.canvas.setAttribute('height', this.image.height)
// }
const x = this.image.width / 2
const y = this.image.height / 2
this.context.clearRect(0,0, this.canvas.width, this.canvas.height) // 清理画布内容
this.context.translate(x, y)
this.context.rotate(90 * Math.PI / 180)