前言
随着科技的发达,在日常生活中我们逐渐的脱离的笔和纸,但往往还有许多场景我们还是需要涂涂画画,不论是开会或者设计等等刚好身边没有笔纸,我们的画板就排上用场了。我们还可以扩展将其作为和键盘鼠标一样的输入设备等等。还有更多的使用场景让我们一起探索。
功能介绍
画板组件是基于HarmonyOS下的JavaScript UI框架开发的一款组件,主要特点如下:
- 支持画笔粗细选择
- 支持画笔颜色定义选中
- 画笔颜色除了默认颜色,可点击色盘,选择自己想要的颜色
- 一键清除画板
- 支持橡皮擦功能
- 支持保存图片功能
注意:
- 保存功能需要api >= 6,得到的是一个base64的数据,可以根据自己的需要自行调整
- 功能操作区域可左右滑动选择
组件使用说明
name="drawing-board" src="../../common/component/drawingBoard.hml"> "getUrl" > -
- // 获取图片信息,可以根据自己的图片组件需要,处理对应的base64 数据
- getUrl(valueUrl){
- console.log('得到图片信息'+JSON.stringify(valueUrl)); // "data:image/png;base64,xxxxxxxx..."
- }
主要代码
组件传值
- // 可以根据自己的实际情况,传入需要的画笔颜色和画笔大小
- props: {
- // 画笔粗细
- brushSizes: {
- type: Array,
- default: [3,8,16]
- },
- // 画笔颜色
- brushColor: {
- type: Array,
- default: ['#ffffff',"#000000","#ff9800",'#3f51b5','#ff5722',"#4caf50"]
- }
初始化画布
- initCanvas(){
- this.canvas = this.$refs.canvas;
- this.canvasTxt = this.canvas.getContext('2d',{ antialias: true });
- this.canvasTxt.strokeStyle = this.signColor;
- this.canvasTxt.lineJoin = "round";
- this.canvasTxt.lineCap = "round";
- this.canvasTxt.globalCompositeOperation = this.penType;
- this.canvasTxt.lineWidth = this.lineWidth;
- }
设置画板工具
- setTool(item,index) {
- console.log(index);
- if(index == 0 || index == 1){
- this.toolOn = index;
- }
- let type = item.type;
- switch(type){
- case 1:
- // 画笔
- this.penType = 'source-over';
- this.canvasTxt.lineWidth = this.lineWidth;
- this.canvasTxt.globalCompositeOperation = this.penType;
- break;
- case 2:
- // 橡皮檫
- this.penType = 'destination-out';
- this.canvasTxt.lineWidth = this.lineWidth;
- this.canvasTxt.globalCompositeOperation = this.penType;
- break;
- case 3:
- this.overwrite();
- break;
- case 4:
- // 保存
- this.savaCanvas();
- break;
- }
- },
画笔颜色选择
- selectColor(color,index) {
- this.colorOn = index;
- this.signColor = color;
- this.canvasTxt.fillStyle = this.signColor;
- this.canvasTxt.strokeStyle = this.signColor;
- this.canvasTxt.lineWidth = this.lineWidth;
- },
画笔粗细设置
- selectSize(size,index) {
- this.sizeOn = index;
- this.lineWidth = size;
- this.canvasTxt.lineWidth = this.lineWidth;
- },
开始画线
- drawLine(beginPoint, controlPoint, endPoint) {
- this.canvasTxt.beginPath();
- this.canvasTxt.moveTo(beginPoint.x, beginPoint.y);
- this.canvasTxt.quadraticCurveTo(
- controlPoint.x,
- controlPoint.y,
- endPoint.x,
- endPoint.y
- );
- this.canvasTxt.stroke();
- this.canvasTxt.closePath();
- },
一键清除功能
- overwrite() {
- this.canvasTxt.clearRect(0, 0, 1920,1920);
- this.points = [];
- this.isDraw = false; //画板标记
- },
保存功能
- savaCanvas(){
- var dataURL = this.$refs.canvas.toDataURL();
- // 保存画板的到的是base64信息
- this.$emit('eventDataurl',dataURL)
}
效果演示