I try to create a canvas (which is a copy of an image) in order to get an array of his RGBA values. What am I doing wrong? Help would be appreciated.
getColorArray(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var file = this.$el.querySelector("#image-preview-image");
ctx.drawImage(file, 10, 10);
const imageData = ctx.createImageData(10, 10);
console.log(imageData);
}
CodePudding user response:
createImageData()
will just create a new array of color points where all the values are 0. You need to use getImageData() to get the data that is already on the canvas.
const getColorArray = () => {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var file = document.querySelector("#image-preview-image");
ctx.drawImage(file, 0, 0);
const imageData = ctx.getImageData(0, 0, 100, 100);
console.log(imageData);
};
getColorArray();
<p>Image:
<img id="image-preview-image" src="data:image/svg xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj4KICA8Y2lyY2xlIGN4PSI1MCUiIGN5PSI1MCUiIHI9IjUwJSIgZmlsbD0iZ3JlZW4iIC8 Cjwvc3ZnPgo=" />
</p>
<p>Canvas:
<canvas id="myCanvas" width="100" height="100"></canvas>
</p>