簡體   English   中英

在鼠標移動中獲取fabric.js中圖像像素的rgb值

[英]get rgb values of pixel of image in fabric.js on mouse move

如何在鼠標移動中獲取fabric.js中圖像的rgb值。 我使用了圖像對象的getFill()方法,但它返回(0,0,0)。 請幫我

FabricJS沒有獲取像素顏色的本機方法。

解決方法是使用本機html5畫布來獲取像素數據:

  • 創建Fabric圖像對象。 請確保將crossOrigin指定為“匿名”,否則畫布將受到安全違規的污染,然后像素數據將不可用。

  • 收聽Fabric的'mouse:move'活動。 當它觸發時,獲取當前鼠標位置並使用本機畫布的context.getImageData來獲取該像素的顏色數組。

祝你的項目好運!

這是annotatede代碼和演示:

 // create a Fabric.Canvas var canvas = new fabric.Canvas("canvas"); // get a reference to <p id=results></p> // (used to report pixel color under mouse) var results = document.getElementById('results'); // get references to the html canvas element & its context var canvasElement = document.getElementById('canvas'); var ctx = canvasElement.getContext("2d"); // create a test Fabric.Image addFabricImage('https://dl.dropboxusercontent.com/u/139992952/multple/colorBar.png'); // listen for mouse:move events canvas.on('mouse:move', function(e) { // get the current mouse position var mouse = canvas.getPointer(ee); var x = parseInt(mouse.x); var y = parseInt(mouse.y); // get the color array for the pixel under the mouse var px = ctx.getImageData(x, y, 1, 1).data; // report that pixel data results.innerHTML = 'At [' + x + ' / ' + y + ']: Red/Green/Blue/Alpha = [' + px[0] + ' / ' + px[1] + ' / ' + px[2] + ' / ' + px[3] + ']'; }); // create a Fabric.Image at x,y using a specified imgSrc function addFabricImage(imgSrc, x, y) { // create a new javascript Image object using imgSrc var img = new Image(); // be sure to set crossOrigin or else // cross-domain imgSrc's will taint the canvas // and then we can't get the pixel data // IMPORTANT!: the source domain must be properly configured // to allow crossOrigin='anonymous' img.crossOrigin = 'anonymous'; // when the Image object is fully loaded, // use it to create a new fabric.Image object img.onload = function() { var fabImg = new fabric.Image(this, { left: 30, top: 30 }); canvas.add(fabImg); } // use imgSrc as the image source img.src = imgSrc; } 
 body { background-color: ivory; } canvas { border: 1px solid red; } 
 <script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script> <p id="results">Move mouse over canvas</p> <canvas id=canvas width=300 height=300></canvas> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM