I have a rectangle and a button. When the user clicks the button, I want the rectangle to get bigger. This is my code:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx.stroke();
var height = 150;
function myFunction(){
height = 300;
}
<button onclick="myFunction()">Click Me!</button>
<canvas id="myCanvas" width="300" height="height" style="border:1px solid #d3d3d3;"></canvas>
Although, nothing happens when I click the button. Help?
height="height" is not a valid value in html.
On click of button you can change the style.height of the canvas
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx.stroke();
var height = 150;
function myFunction(){
c.style.height = '300px'; // changed here
}
DEMO
Edit
Remove the width from the html, add it through css
JS
function myFunction(){
c.style.height ='300px';
}
CSS
#myCanvas{
width:300px
}
HTML
<canvas id="myCanvas" style="border:1px solid #d3d3d3;"></canvas>
DEMO 2
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx.stroke();
function myFunction(){
c.style.height ='300px';
}
#myCanvas{
width:300px
}
<button onclick="myFunction()">Click Me!</button>
<canvas id="myCanvas" style="border:1px solid #d3d3d3;"></canvas>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With