我试图制作一个颜色选择器。我的代码以某种方式在getImageData之后停止。我无法找到解决方案......
是否有其他方法可以获得像素的值? 或问题是我试图使用图片的链接?
> function drawImage() {
> var image = new Image();
> image.src = imageSrc;
> image.onload = function() {
> context.clearRect(0, 0, canvas.width, canvas.height);
> context.drawImage(image, 0, 0, image.width, image.height);
>
> $('#cPicker').mousemove(function(e) {
> if (previewOn)
> {
> var canvasOffset = $(canvas).offset();
> var x = Math.floor(e.pageX - canvasOffset.left);
> var y = Math.floor(e.pageY - canvasOffset.top);
>
> alert(x + ', ' + y);
>
> var imageD = context.getImageData(x, y, 1, 1);
> var pixel = imageD.data;
>
> var pixelColor = 'rgb(' + pixel[0] + ', ' + pixel[1] + ', ' + pixel[2] + ')';
> $('preview').css('backgroundColor', pixelColor);
>
> $('#rValue').val(pixel[0]);
> $('#gValue').val(pixel[1]);
> $('#bValue').val(pixel[2]);
> $('#rgbValue').val(pixel[0]+','+pixel[1]+','+pixel[2]);
>
> var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
> $('#hexValue').val('#' + ('0000' + dColor.toString(16)).substr(-6));
> };
> });
>
> $('#cPicker').click(function(e) {
> previewOn = !previewOn;
> });
> };
};
答案 0 :(得分:0)
似乎与Saving canvas with CanvasRenderingContext2D filter
重复我还创建了一个测试小提琴:https://jsfiddle.net/k6Laknva/1/
var imageSrc = "https://jsfiddle.net/img/logo.png";
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var previewOn = true;
function drawImage() {
var image = new Image();
image.src = imageSrc;
image.onload = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, image.width, image.height);
$('#cPicker').mousemove(function(e) {
if (previewOn) {
var canvasOffset = $(canvas).offset();
var x = Math.floor(e.pageX - canvasOffset.left);
var y = Math.floor(e.pageY - canvasOffset.top);
console.log(x + ', ' + y);
var imageD = context.getImageData(x, y, 1, 1);
var pixel = imageD.data;
var pixelColor = 'rgb(' + pixel[0] + ', ' + pixel[1] + ', ' + pixel[2] + ')';
$('preview').css('backgroundColor', pixelColor);
$('#rValue').val(pixel[0]);
$('#gValue').val(pixel[1]);
$('#bValue').val(pixel[2]);
$('#rgbValue').val(pixel[0]+','+pixel[1]+','+pixel[2]);
var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0];
$('#hexValue').val('#' + ('0000' + dColor.toString(16)).substr(-6));
};
});
$('#cPicker').click(function(e) {
previewOn = !previewOn;
});
};
};
drawImage();
这在Chrome 56中运行良好,但在Firefox 52中失败:/