Reputation: 107
i've been using FabricJS for a couple days now, and i'm having trouble grabbing the value of my dropdown menu so I can properly apply the desired shape with an eventlistener of "click. So when I hit the dropdown menu and select "rectangle" and hit the button, it should generate a rectangle. Here is my code:
HTML:
<p>Choose a Shape</p>
<select id="shapesId">
<option value="square">Square</option>
<option value="rectangle">Rectangle</option>
<option value="triangle">Triangle</option>
<option value="circle">Circle</option>
<option value="polygon">Polygon</option>
<option value="ellipse">Ellipse</option>
<option value="line">Line</option>
</select>
<button id="realShapes">Go!</button>
so when we hit "Go!" I want to get the value of whatever is selected through the option of shapes. And now here is my Javascript:
const shapes = document.getElementById("shapesId");
const e = shapes.value;
const clickShapes = document.getElementById("realShapes");
clickShapes.addEventListener("click", () => {
if(e === "Rectangle") {
const rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'black',
width: 70,
height: 70,
angle: 45
});
canvas.add(rect);
}
canvas.renderAll();
})
I am so lost right now,and been trying to figure this out for hours, any help would be appreciated. Thank you to whoever is reading this!
Upvotes: 2
Views: 60
Reputation: 8063
Try to use this to get the shapesid selected value (will store the value to xvalue) :
var xvalue = document.getElementById("shapesId").options[document.getElementById("shapesId").selectedIndex].value;
Additional Information (you may use the following as a workable example):
<canvas id="myCanvas" width="400" height="400"
style="border:1px solid #ff0000;">
</canvas>
<br>
<p>Choose a Shape</p>
<select id="shapesId">
<option value="">Please select</option>
<option value="rectangle">rectangle</option>
<option value="circle">circle</option>
</select>
<input type=button value="DRAW" onclick="javascript:draw();">
<script>
function draw() {
var xvalue = document.getElementById("shapesId").options[document.getElementById("shapesId").selectedIndex].value;
if (xvalue=="rectangle") {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 400, 400);
var ctx = c.getContext("2d");
//ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();
}
if (xvalue=="circle") {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 400, 400);
var ctx = c.getContext("2d");
//ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
}
}
</script>
Upvotes: 1