从屏幕外画布上绘制的图像像素中采样颜色时出现问题

时间:2011-09-13 08:40:06

标签: javascript image html5 canvas sample

我需要从图像中采样像素颜色,但似乎我无法正确使用它。我加载图像并将其绘制到离屏画布,然后我尝试采样像素颜色,但我总是得到0值。

我的代码:

// Create canvas and set context
var canvas = document.createElement('canvas');
canvas.width = 8;
canvas.width = 8;
var context = canvas.getContext('2d');

// Setup image
var image = new Image();
image.src = 'img.png';
image.onload = function(){
    context.drawImage(image, 0, 0);
}

// Sample a random pixel from the canvas
var x = Math.floor(Math.random()*8);
var y = Math.floor(Math.random()*8);
var pixelInfo = context.getImageData(x,y,1,1);
var rgbaVal = pixelInfo.data;
alert('Image: '+image.src+'\n\nR: '+rgbaVal[0]+'\nG: '+rgbaVal[1]+'\nB: '+rgbaVal[2]+'\nA: '+rgbaVal[3]+'\n\nCoords: '+x+', '+y);

我没有错误,如果我尝试在屏幕画布上绘制图像,则图像会正确绘制。我无法找到问题

2 个答案:

答案 0 :(得分:2)

因为尚未加载和绘制图像。你在触发onload后绘制它,然后你也应该得到RGB值。

image.onload函数将在您的采样函数之后触发,因此您现在只需对空白画布进行采样。

答案 1 :(得分:1)

<canvas id="canvas1" width="200", height="200" style="background:red;">Random Canvas</canvas>
<script>

    var canvas = document.getElementById("canvas1");
    //canvas.width = 200;
    //canvas.width = 200;
    var context = canvas.getContext('2d');

    // Setup image
    var image = new Image();
    image.src = "img/image.jpg";

    image.onload = function()
    {

       context.drawImage(image, 0, 0);

       var x = Math.floor(Math.random()*200);
       var y = Math.floor(Math.random()*200);
       var pixelInfo = context.getImageData(x,y,1,1);
       var rgbaVal = pixelInfo.data;

       alert('Image: '+image.src+'\n\nR: '+rgbaVal[0]+'\nG: '+rgbaVal[1]+'\nB: '+rgbaVal[2]+'\nA: '+rgbaVal[3]+'\n\nCoords: '+x+', '+y);

    }

    // Sample a random pixel from the canvas

</script>