2017-03-09 72 views
1

我正在試着製作一個colorpicker。我的代碼以某種方式在getImageData之後停止。我找不到解決方案...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

好像的副本: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:/