Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Rectangle Height with Button

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?

like image 225
Nathan Chan Avatar asked Nov 30 '25 07:11

Nathan Chan


1 Answers

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>
like image 66
brk Avatar answered Dec 02 '25 20:12

brk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!