我有一个有效的jquery代码片段,它可以很好地获取我的颜色选择器farbtastic的十六进制值。我遇到的问题是用paintbrushjs将其应用为色调。 Hex 只是不会传输到图像的 id,并且不会更新 data-tint-pb-colour 选项。因此,我可能正在考虑 php 选项,但希望首先输入可能的修复方案,因为我已经工作了 3 天,但无法使其正常工作。
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#demo').hide();
$('#picker').farbtastic('#color');
});
$(document).ready(function() {
var picker = $.farbtastic('#picker');
picker.linkTo(function onColorChange(color) {
$('filter-tint').attr('data-pb-tint-colour',color)
console.log(color, "hello world!");
});
});
HTML
<form action="" style="width: 400px;">
<div class="form-item"><label for="color">Color:</label><input type="text" id="color" name="color" value="#123456" /></div><div id="picker"></div>
</form>
<img id="filter-tint" class="filter-tint" src="http://preview.88kcikfcuw4mfgvi8ckrxvjrndu6jemi01t025rhda6skyb9.box.codeanywhere.com/images/Layer2.png" data-pb-tint-opacity="0" data-pb-tint-colour="#ffffff"/>
我基本上已经碰壁了。不知道如何进行这项工作。 fiddle.
最佳答案
如果你不介意不使用PaintbrushJS,我发现this answer它建议在您的图像上覆盖一个半透明的 div。所以基本上,您将 div 的尺寸和位置设置为等于图像的尺寸和位置。然后你设置它的背景颜色。由于您希望颜色是透明的,因此您需要为背景颜色设置一个 rgba 值。但是,farbtastic 返回十六进制颜色,因此您必须将其转换为 rgba 值。
首先添加div:
<div id="overlay" class="overlay"></div>
类覆盖层在加载时将具有以下 css:
.overlay
{
display: block;
position: absolute;
}
然后添加以下代码:
$(document).ready(function() {
$('#picker').farbtastic('#color');
var $picker = $.farbtastic('#picker');
SetTintColor($("#color").val()); // Set tint at load too
$picker.linkTo(function(hexColor) {
SetTintColor(hexColor);
});
});
function SetTintColor(hexColor) {
var $filterImage = $('#filter-tint');
var $overlay = $("#overlay");
// Set the div's dimensions and position equal to the image's dimensions and position
$overlay.css({
"height": $filterImage.height(),
"width": $filterImage.width(),
"top": $filterImage.offset().top + "px",
"left": $filterImage.offset().left + "px"
});
// The farbtastic plugin returns a hex color, but we want to set a rgba as the div's background-color,
// so it can be transparent.
var rgb = hexToRgb(hexColor);
var opacity = 0.5; // This can be changed for a dynamic value
// Concatenate the rgb's values + opacity to obtain a string representing the rgba
var rgbaColor = "rgba(" + rgb.r + ", " + rgb.g + ", " + rgb.b + ", " + opacity + ")";
$overlay.css("background-color", rgbaColor);
// Change the color input's background-color
var $colorInput = $("#color");
$colorInput.val(hexColor);
$colorInput.css("background-color", hexColor);
}
// Taken from https://stackoverflow.com/a/5624139/2835243
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
因此,如果您仅将 PaintbrushJS 用于色调,我建议您只需执行上述操作,因为它更轻,并且因为 PaintbrushJS 似乎存在一些问题。
关于javascript - 从 Farbtastic 获取十六进制值并转换为 RGB 以在 php 中的 imagefilter 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31657365/