本文主要是介绍konva.js 工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
konva.js 工具类
class KonvaCanvas {/*** 初始化画布* @param {String} domId 容器dom id*/constructor(domId) {this.layer = null;this.stage = null;this.scale = 1;this.init(domId);}/*** 聚焦到指定元素* @param {String} elementId 元素dom id*/focusOn(elementId) {if (!this.layer || !this.stage || !elementId) return;var element = this.stage.find("#" + elementId)[0];console.log(element.position());let x = this.stage.width() * 0.5 - element.position().x;let y = this.stage.height() * 0.5 - element.position().y;this.stage.x(x);this.stage.y(y);// this.layer.draw();}/*** 绘制图片* @param {String} url 图片路径* @param {String} id 唯一标识* @param {Number} x 横坐标* @param {Number} y 纵坐标* @param {Number} zoom 缩放比例* @param {Number} rotate 旋转角度*/drawImage(url, id, x = 0, y = 0, zoom = 1.0, rotate = 0) {return new Promise((resolve, reject) => {var img = new Image();img.src = url;const img_w = img.width * zoom;const img_h = img.height * zoom;const that = this;img.onload = function () {var kImage = new Konva.Image({image: img,x: x,y: y,width: img_w,height: img_h,offset: {// offset的设置是使得围绕中心旋转x: img_w / 2,y: img_h / 2,},id: id,});kImage.rotate(rotate);that.layer.add(kImage);// that.layer.draw();console.log("图片加载完成");that.layer.batchDraw(); //重绘resolve(kImage);};});}/*** 更新元素属性信息* @param {String} id 元素id* @param {Object} attr 元素属性 {}*/updateElement(id, attr) {if (!this.layer || !this.stage) return;var shape = this.stage.find("#" + id)[0];shape.setAttrs(attr);this.layer.draw();}/*** 绘制线* @param {Array} points 点位坐标 [x1, y1, x2, y2, x3, y3]* @param {String} id 唯一标识* @param {Number} lineWidth 线宽* @param {String} color 颜色* @returns*/drawLine(points, id, lineWidth = 1, color = "#ffffff") {if (!this.layer) return;var line = new Konva.Line({points: points || [],stroke: color,strokeWidth: lineWidth,lineCap: "round",lineJoin: "round",tension: 0.5,id: id,});this.layer.add(line);}/*** 销毁画布*/destroyed() {if (this.layer) {this.layer.destroyChildren();this.layer.draw();}}// ========================================== 私有方法init(domId) {if (!domId) {return;}const container = document.getElementById(domId);var width = container.clientWidth;var height = container.clientHeight;var stage = new Konva.Stage({container: domId,width: width,height: height,draggable: true,});var layer = new Konva.Layer();stage.add(layer);this.stage = stage;this.layer = layer;this.stage.on("wheel", e => {const direction = e.evt.deltaY > 0 ? -0.1 : 0.1;this.scale = this.scale + direction;this.stage.scaleX(this.scale);this.stage.scaleY(this.scale);this.stage.getPointerPosition();// this.layer.draw();// this.stage.draw();this.layer.batchDraw(); //重绘});}// ========================================== 私有方法 end
}export default KonvaCanvas;
这篇关于konva.js 工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!