先说明一下采用的技术以及用途:技术采用 html2canvas+draggable-vue-directive。html2canvas将HTML内容写入Canvas生成图片,这里采用双击图片生成input框模拟html字,采用draggable-vue-directive技术在图片范围内拖动input。
效果如图:
代码采用vue框架来写,这里还是demo写的很随意如果有些不用的可自行删除,仅供参考。
直接上代码:
在这里插入代码片
<template>
<div>
<el-button @click="showModal">选择封面</el-button>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="50%"
>
<div ref="addImage">
<div :style="{ margin: `10px,10px,10px,10px` }">
<span>色选</span>
<colorPicker v-model="color" @change="colorChange"></colorPicker>
<span style="margin-left:20px">大小</span>
<el-input-number size="mini" v-model="num" @change="numChange"></el-input-number>
</div>
<div ref="capture" class="container" @dblclick="handleClick" style="background('/src/assets/img/img02.jpg)">
<input type="text"
v-for="(item,i) of inputList"
:key="i"
ref="handleId"
class="input"
v-focus
v-draggable="draggableWithBoundries"
:style="{
border: 'none',
left: `${item.x}px`,
top: `${item.y}px`,
}"
>
</div>
</div>
<span slot="footer" class="dialog-footer">
<el-button @click="cancle">取 消</el-button>
<el-button type="primary" @click="handleOk">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import html2canvas from 'html2canvas';
import { Draggable, DraggableValue } from "draggable-vue-directive";
export default {
data() {
return {
input: '',
dialogVisible: true,
color: '#606266',
inputList: [],
index: 0,
num: 20,
draggableWithBoundries: {
},
};
},
directives: {
Draggable,
focus: {
inserted: function(el,bind,vnode) {
el.focus();
}
},
},
mounted() {
this.$nextTick(() => {
this.draggableWithBoundries.boundingElement = this.$refs.capture;
this.draggableWithBoundries.boundingRectMargin = {
top: 2,
bottom: 2,
left: 2,
right: 2,
};
})
},
methods: {
showModal() {
},
cancle() {
},
handleOk() {
html2canvas(this.$refs.capture, { useCORS: true }).then(canvas => {
console.log(canvas)
// let ctx = canvas.getContext('2d');
if(document.querySelector('canvas')) {
this.$refs.capture.appendChild(canvas);
const base64 = canvas.toDataURL();
this.inputList = [];
}
// ctx.clearRect(0,0,canvas.width,canvas.height)
// doc.style.background = "url('"+base64+"')";
});
},
colorChange(e) {
if(document.getElementsByClassName('input').length>=1) {
document.getElementsByClassName('input')[this.index-1].style.color = e;
}
},
numChange(currentValue, oldValue) {
if(document.getElementsByClassName('input').length>=1) {
document.getElementsByClassName('input')[this.index-1].style.fontSize = currentValue + 'px';
}
},
handleClick(e) {
let item = { x: e.offsetX, y: e.offsetY };
this.inputList.push(item);
this.index++;
},
},
};
</script>
<style scoped lang="scss">
.container {
width: 100%;
height: 200px;
position: relative;
background: url("../../assets/img/img02.jpg") no-repeat;
}
.input {
width:150px;
position: absolute;
background:transparent;
color: #fff;
font-size:20px;
font-weight:600;
}
/deep/ .m-colorPicker .box{
z-index: 1;
}
</style>