I have a written a code which randomly generates a specified number of non-overlapping circles onto a canvas element. I want my code to take an image and map the colors from the image onto the circles on the canvas. For ease of use I created two canvases side by side each 300px by 300px.
var canvas = document.querySelector('canvas');
canvas.width = 300;
canvas.height= 300;
var c = canvas.getContext('2d');
var can=document.getElementById("hide");
can.width = 300;
can.height = 300;
var ctx=can.getContext("2d");
var img=document.getElementById("taco");
ctx.drawImage(img,10,10);
I have a circles class which requires all circles to have an x, y, radius, and color.
class Circles {
constructor(x,y,radius){
this.x =x;
this.y = y;
this.radius = radius;
this.color= color;
}
draw() {
c.beginPath()
c.arc(this.x,this.y,this.radius,0,Math.PI *2, false);
c.strokeStyle = 'black';
c.stroke();
c.fillStyle =this.color;
c.fill();
}
}
Lastly I run a for loop to generate a specified number of circles and check if any circles overlap. I am using getImageData
to attempt to find the pixel color of the image on one of the canvases and use that color to fill a circle on the other canvas.
function setup() {
for(let i=0; i<10;i++){
let x = Math.random()*300;
let y = Math.random()*300;
let pixel= ctx.getImageData(x,y,1,1)
let data = pixel.data;
let color = `rgba(${data[0]},${data[1]},${data[2]},${(data[3]/255)})`
let circle = new Circles(x,y,2,color);
let overlapping = false
for(let j=0; j< circleArray.length; j++){
let other = circleArray[j];
let d = dist(circle.x,other.x,circle.y,other.y);
if(d < circle.radius + other.radius){
overlapping = true;
break;
}
}
if(overlapping== false){
circleArray.push(circle);
//console.log(circleArray);
}
}
}
I am getting an error that seems common in Canvas:
client.js:49 Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
I tried the solutions on this page but the image I am using is a downloaded png and none of those solutions seem to work.
How to fix getImageData() error The canvas has been tainted by cross-origin data?