ARTICLE AD BOX
I'm using a black colored circle as the mask of a red rectangle that's 100x100, which is 10,000 pixels. The mask looks great and gives a nice red circle, but when I try to count all the red pixels in the result, I get 10,000 (the original rectangle) when I should get a smaller number (from the circle). I know I need to flatten the mask somehow and I've found several examples of how to do this, but none of them work and instead of cluttering this example with everything I've tried I'm just explaining the problem and I think there's only a few lines more of code that are needed.
window.addEventListener("load", (event) => {
console.log("Page is fully loaded");
init();
});
function init() {
//var myCanvas = document.querySelector("#myCanvas");
var redColorCount=0;
var stage = new createjs.Stage("myCanvas");
// 1. Create your masked graphic (or container)
var shape = new createjs.Shape();
shape.graphics.beginFill("red").drawRect(0, 0, 100, 100); // Red Square
var maskShape = new createjs.Shape();
maskShape.graphics.beginFill("#000").drawCircle(50, 50, 50); //Black Circle for mask
console.log(maskShape.x);
shape.mask = maskShape;
shape.cache(0, 0, 100, 100);
var cacheCanvas = shape.cacheCanvas;
var ctx = cacheCanvas.getContext("2d");
var imageData = ctx.getImageData(0, 0, 100, 100).data;
console.log(imageData);
stage.addChild(shape);
shape.uncache();
stage.update();
console.log("Length: "+imageData.length);
for (var i = 0; i < imageData.length; i += 4) {
if ((imageData[i] == 255) && (imageData[i+1] == 0) && (imageData[i+2] == 0)){
redColorCount++;
}
}
console.log("redColorCount: "+redColorCount);
}
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<canvas id="myCanvas" width="500" height="350"></canvas>
