vue实现马赛克功能
今天小猪实现了一个有趣的马赛克功能,感兴趣的可以看看。。。。
一、安装image-mosaic
npm install image-mosaic
小猪也就不墨迹了直接上代码
二、实现马赛克代码
<template>
<div id="box">
<canvas id="canvas"></canvas>
<button id='drawAll'>一键加码</button>
<button id='clearAll'>还原</button>
</div>
</template>
<script>
import Mosaic from 'image-mosaic';
export default {
name: 'Masaic',
data() {
return {
imgSrc: require('../assets/mein.jpeg')
}
},
mounted() {
this.initMosaic()
},
methods: {
initMosaic () {
this.drawImageToCanvas().then(ctx => {
const mosaic = new Mosaic(ctx)
const MouseEvents = {
init () {
mosaic.context.canvas.addEventListener('mousedown', MouseEvents.mousedown)
},
mousedown () {
mosaic.context.canvas.addEventListener('mousemove', MouseEvents.mousemove)
document.addEventListener('mouseup', MouseEvents.mouseup)
},
mousemove (e) {
if (e.shiftKey) {
mosaic.eraseTileByPoint(e.layerX, e.layerY)
return
}
mosaic.drawTileByPoint(e.layerX, e.layerY)
},
mouseup () {
mosaic.context.canvas.removeEventListener('mousemove', MouseEvents.mousemove)
document.removeEventListener('mouseup', MouseEvents.mouseup)
}
}
MouseEvents.init()
document.querySelector('#drawAll').addEventListener('click', () => {
mosaic.drawAllTiles()
})
document.querySelector('#clearAll').addEventListener('click', () => {
mosaic.eraseAllTiles()
})
})
},
drawImageToCanvas() {
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
let imageUrl
if (this.imgSrc) {
imageUrl = this.imgSrc
}
return new Promise((resolve) => {
const image = new Image()
image.crossOrigin = 'Annoymous'
image.onload = function () {
canvas.width = image.width
canvas.height = image.height
ctx.drawImage(this, 0, 0, image.width, image.height)
resolve(ctx)
}
image.src = imageUrl
})
}
}
}
</script>
<style></style>
谢谢各位小主的观赏。。。。