[英]trigger event in jQuery and listen to it in fabricjs (or js)
我需要一些方法来触发事件并在 FabricJs 中收听它。 这个想法是,使用jQuery
选择器我得到元素,当有人点击这些元素中的任何一个时, fabricjs
应该改变 Canvas 背景。
$('#background-selector .background-img img').on("click", (el) => {
// so here I need to trigger event and also pass el.data to the event
// el.data contains image name that should be used to change canvas background
});
我是fabricjs
和javascript
(没有jquery
)的新手,所以需要一些关于这应该如何相互工作的指导。
我也是fabric.js的新手......因为你的问题,所以谢谢;)
花了一段时间才找到如何从 canvas 外部触发事件。 我使用 JavaScript new Event 和 .createEvent()尝试了所有操作......但这只是失败了,因为“自定义事件”只能应用于 DOM 元素,而织物 canvas 内的对象则不是。
所以.. 探索 fabric.js 文档,我发现他们处理了一些从 canvas 内部的动作触发的事件,但这不是我需要的......虽然知道如何监听事件很有用。
我终于找到了observable
的命名空间。 它包括一个fire()
方法,该方法正是关于触发事件的。
然后,我在 canvas object 事件处理程序中阻止了如何使更改“出现”在 canvas 中。 It seems that property changes on the canvas itself, using a method like .setBackgroundImage() , needs a callback to re-render and changes on canvas objects need the object to be re-added to the canvas.
所以这是一个简单的演示,其中有两个 DOM 按钮:
// create a wrapper around native canvas element (with id="c") var canvas = new fabric.Canvas('c') var render_callback = canvas.renderAll.bind(canvas) // create a rectangle object var rect = new fabric.Rect({ left: 100, top: 100, fill: 'red', width: 20, height: 20 }); // "add" rectangle onto canvas canvas.add(rect); // ======================================== // Canvas object event handlers rect.on('btn1_click', function(e) { console.log('custom event #1', e.data); // Change the fill color and re-add the object rect.set('fill', e.data) canvas.add(rect); }); canvas.on('btn2_click', function(e) { console.log('custom event #2', e.data); // Set a background image, // the callback (2nd argument) is needed to re-render canvas.setBackgroundImage(e.data, render_callback) }); // ======================================== // DOM event handlers for the buttons $("#change_color").on("click", function(){ console.log($(this).data("color")) // Fire the canvas event and pass the image url rect.fire("btn1_click", {data: $(this).data("color")}) }) $("#change_image").on("click", function(){ console.log($(this).data("img")) // Fire the canvas event and pass the image url canvas.fire("btn2_click", {data: $(this).data("img")}) })
#c{ border: 1px solid lightgrey; } button{ margin: 2em 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.0/fabric.min.js"></script> <canvas id="c" width=220 height=220></canvas> <button id="change_color" data-color="blue">Click me to change the rect color</button> <button id="change_image" data-img="https://via.placeholder.com/220x220.png">Click me to add an image</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.