I am using fabricJS to draw different shapes over a fabric canvas. My canvas as an image object and that is scaled. Now when I draw a star without using this ctx.setTransform(1, 0, 0, 1, 0, 0); means comment this ctx.setTransform then Fabric Star object is selectable but when I use this ctx.setTransform(1,0,0,1,0,0) then fabric star object is not selectable.
I have tried this canvas.setViewportTransform([1, 0, 0, 1, 0, 0]); to transform but in this case my stars are not drawing at required place means due to scaling they draw at different X,Y points.
function drawStars(data){
drawStar(data.x,data.y,data.spikes,5,1,data.color);
}
function drawStar(cx, cy, spikes, radius, isRGB, statusColor) {
var innerRadius = radius;
var outerRadius = radius / 2;
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
var starPoints = [];
starPoints.push({ x: cx, y: cy - outerRadius });
for (i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
starPoints.push({ x: x, y: y });
rot += step;
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
starPoints.push({ x: x, y: y });
rot += step;
}
starPoints.push({ x: cx, y: cy - outerRadius });
var starPolygon = new fabric.Polygon(starPoints, {
fill: (isRGB) ? statusColor : "#" + statusColor,
selectable: true,
name: "Polygon",
type: 'normal'
});
canvas.add(starPolygon);
canvas.renderAll();
//canvas.setActiveObject(starPolygon);
canvas.bringForward(starPolygon);
canvas.bringToFront(starPolygon);
}
scaleAndPositionImage = function () {
canvas.clear();
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.globalAlpha = 1; // reset alpha
//ctx.clearRect(0, 0, canvasWidth, canvasHeight);
//canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
var objects = canvas.getObjects();
for (let i = 0; i < objects.length; i++) {
objects[i].setCoords();
}
//setCanvasZoom();
if (bgImage.width === 0) bgImage.width = canvasWidth;
if (bgImage.height === 0) bgImage.height = canvasHeight;
var canvasAspect = canvasWidth / canvasHeight;
var imgAspect = bgImage.width / bgImage.height;
if (canvasAspect >= imgAspect) {
scaleFactor = canvasWidth / bgImage.width;
canvasLeft = 0;
canvasTop = -((bgImage.height * scaleFactor) - canvasHeight) / 2;
} else {
scaleFactor = canvasHeight / bgImage.height;
canvasTop = 0;
canvasLeft = -((bgImage.width * scaleFactor) - canvasWidth) / 2;
}
if (scaleFactor === Infinity) { scaleFactor = 1; }
canvasTop = 0;
canvasLeft = 0;
//console.log("Top: " + canvasTop, "Left: " + canvasLeft, "ScaleFactor: " + scaleFactor, "img Width: " + bgImage.width, "canvas Width: " + canvasWidth);
bgImage.set({
"name": "image",
"left": canvasLeft,
"top": canvasTop,
"scaleX": canvas.width / bgImage.width,
"scaleY": canvas.height / bgImage.height,
"selectable": false,
hoverCursor: "move"
});
//console.log(canvas);
canvas.add(bgImage);
canvas.renderAll();
drawStar(lotsData);
}
Please help.