将鼠标悬停在画布上(使用Fabric js进行免费绘图)时,我想模仿鼠标按下/单击事件,并让用户创建其绘图/路径。
这可能吗?
有关在Fabric上处理事件的更多信息-https://github.com/fabricjs/fabric.js/wiki/working-with-events#demos-and-examples
我正在使用Vuejs,但完全可以使用它来寻求解决方案!
var app = new Vue({
el: '#app',
data(){
return {}
},
mounted(){
var canvas = new fabric.Canvas('canvas');
canvas.isDrawingMode = true
canvas.setHeight(window.innerHeight)
canvas.setWidth(window.innerWidth)
canvas.freeDrawingBrush.color = 'blue'
canvas.freeDrawingBrush.width = 40
},
methods: {}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<!-- Draw as if I've clicked BUT when hovering over canvas -->
<canvas id="canvas"></canvas>
</div>
答案 0 :(得分:0)
由于与isDrawingMode
相关的事件处理程序是通过鼠标向上和向下按下触发的,因此一种可能的解决方案是自定义这些处理程序以确保:
这是fabric.js处理这些事件的原始代码:http://fabricjs.com/docs/fabric.js.html(第11431至11472行)
这是我的样品
var enableDrawingMode = false;
var app = new Vue({
el: '#app',
mounted(){
var canvas = new fabric.Canvas('canvas');
canvas.isDrawingMode = true
canvas.setHeight(window.innerHeight)
canvas.setWidth(window.innerWidth)
// set up canvas drawing logic based on original mouse down event
canvas._isCurrentlyDrawing = true;
canvas. _onMouseDownInDrawingMode = function(e) {
if (this.getActiveObject()) {
this.discardActiveObject(e).requestRenderAll();
}
if (this.clipTo) {
fabric.util.clipContext(this, this.contextTop);
}
this._handleEvent(e, 'down');
}
canvas._onMouseMoveInDrawingMode = function(e) {
var pointer = this.getPointer(e);
if (!enableDrawingMode) {
console.log('enable original mouse move event only one')
enableDrawingMode = true;
this.freeDrawingBrush.onMouseDown(pointer);
}
this.freeDrawingBrush.onMouseMove(pointer);
this.setCursor(this.freeDrawingCursor);
this._handleEvent(e, 'move');
}
canvas._onMouseUpInDrawingMode = function(e) {
if (this.clipTo) {
this.contextTop.restore();
}
this._handleEvent(e, 'up');
}
canvas.freeDrawingBrush.color = 'blue'
canvas.freeDrawingBrush.width = 40
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<!-- Draw as if I've clicked BUT when hovering over canvas -->
<canvas id="canvas"></canvas>
</div>
具有替代功能,可实现鼠标移动时的绘制。
答案 1 :(得分:0)
let canvas = new fabric.Canvas('canvas');
canvas.isDrawingMode = true;
canvas.on('mouse:move', function (event) {
this._onMouseDownInDrawingMode(event);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/451/fabric.min.js"></script>
<canvas id="canvas" style="border: 1px solid #000"></canvas>