gpt4 book ai didi

javascript - 在鼠标移动时获取 fabric.js 中图像像素的 rgb 值

转载 作者:太空狗 更新时间:2023-10-29 14:08:00 29 4
gpt4 key购买 nike

如何在鼠标移动时获取 fabric.js 中图像的 rgb 值。我使用图像对象的 getFill() 方法,但它返回 (0,0,0)。请帮助我

最佳答案

FabricJS 没有获取像素颜色的 native 方法。

解决方法是使用原生 html5 Canvas 来获取像素数据:

  • 创建您的 Fabric 图像对象。请务必将 crossOrigin 指定为“匿名”,否则 Canvas 将因安全违规而受到污染,然后像素数据将不可用。

  • 监听 Fabric 的“鼠标:移动”事件。当它触发时,获取当前鼠标位置并使用 native Canvas 的 context.getImageData 获取该像素的颜色数组。

祝你的项目好运!

这是带注释的代码和演示:

// 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://cdn.pixabay.com/photo/2019/12/12/05/34/afro-4689826_1280.jpg');

// listen for mouse:move events
canvas.on('mouse:move', function(e) {

// get the current mouse position
var mouse = canvas.getPointer(e.e);
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>

关于javascript - 在鼠标移动时获取 fabric.js 中图像像素的 rgb 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26776436/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com