<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../fabric.js"></script> </head> <body> <canvas id="c" width="600" height="600" style="border: 1px dotted #adadad;"> </canvas> <script> var canvas = this.__canvas = new fabric.Canvas('c') fabric.Object.prototype.transparentCorners = false canvas.on('mouse:over',function(e) { e.target.set('fill', 'red') //e.target获取触发事件的对象 canvas.renderAll() //重新渲染 必须的 所有对canvas的修改,包括在其中添加删除对象,以及对象参数的修改,都需要调用渲染方法才能显示出来 }) canvas.on('mouse:out', function(e) { e.target.set('fill', 'green'); canvas.renderAll(); }) for (var i = 10; i--;) { var dim = fabric.util.getRandomInt(30, 60); //30-60的随机整数 var klass = ['Rect', 'Triangle', 'Circle'][fabric.util.getRandomInt(0, 2)]; //随机生成矩形,三角形,圆形 var options = { top: fabric.util.getRandomInt(0, 600), left: fabric.util.getRandomInt(0, 600), fill: 'green' }; if (klass == 'Circle') { options.radius = dim } else { options.width = dim; options.height = dim; } canvas.add(new fabric[klass](options)) } </script> </body> </html>
mouse:move示例↓
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../fabric.js"></script> </head> <body> <canvas id="c" width="600" height="600"></canvas> <script> var canvas = this.__canvas = new fabric.Canvas('c'); fabric.Object.prototype.transparentCorners = false fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center' fabric.loadSVGFromURL('./135.svg', function(objects) { var obj = objects[0].scale(0.25); obj.originX = 'center' obj.originY = 'center' canvas.centerObject(obj) canvas.add(obj) obj.clone(function(c) { canvas.add(c.set({ left: 100, top: 100, angle: -15 })); }) obj.clone(function(c) { canvas.add(c.set({ left: 480, top: 100, angle: 15 })); }) obj.clone(function(c) { canvas.add(c.set({ left: 100, top: 400, angle: -15 })); }) obj.clone(function(c) { canvas.add(c.set({ left: 480, top: 400, angle: 15 })); }) canvas.on('mouse:move', function(options) { var p = canvas.getPointer(options.e) canvas.forEachObject(function(obj) { var distX = Math.abs(p.x - obj.left), distY = Math.abs(p.y - obj.top), dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2))); console.log(dist, distX, distY) //画布上所有元素循环,p对应的值最小,即opacity最大 obj.set('opacity', 1 / (dist / 20)); }); canvas.renderAll() }) }) </script> </body> </html>
以上效果,鼠标移入的元素不透明度较大,其他元素不透明度较小