I Have the following code :
<html>
<head>
</head>
<body>
<canvas id="canvasId" width="300" height="300"></canvas>
<script>
function square() {
var ctx = document.getElementById('canvasId').getContext('2d');
var col= document.getElementById("clr");
ctx.beginPath();
ctx.rect(10, 10, 70, 70);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = 'black';
ctx.stroke();
}
function triangle () {
var canvas = document.getElementById('canvasId');
var context = canvas.getContext('2d');
var col= document.getElementById("clr");
context.beginPath();
context.rect(85, 80, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 2;
context.strokeStyle = 'black';
context.stroke();
}
</script>
<p>Color <input type="color" id="clr" value="" /></p>
<input type="button" value="square" onclick="square()" />
<input type="button" value="triangle" onclick="triangle()" />
</body>
</html>
I have a problem on this question, I want when the user choose the color and click on square or triangle, it will draw it with the color that he/she choose, what should I change and add ?
You need to replace the second
rect(...)call with something that actually draws a triangle, and you can easily get the color from the input field by accessing itsvalueattribute.Click here for my fork of your jsFiddle.
The relevant lines for accessing the input value are here:
Now for the triangle drawing (assuming you wanted an isosceles triangle to fit the original rectangle):