Canvas renders rectangle rather than square

here is the codepen link
http://codepen.io/pdxSherpa/pen/HImwB

Am trying to create an orange square w/in the blue canvas. & the code is correct. but it looks like the canvas width is affecting the rectangle w/in? It should be square, i have seen it square before…
Any canvas specialist could please advs?
thx
D

I found that you have to set the width and height of the canvas as attributes of the canvas tag. Setting them as CSS properties won’t work correctly. This code works:

<html lang="en">
<head>
<meta charset="UTF-8" />
<style type="text/css">
#myCanvas{
background:#0071c5;
margin-left:50px;
}
</style>
<script type="text/javascript">
function draw(){
    var ctx = document.getElementById("myCanvas").getContext("2d");
    ctx.strokeStyle="#ffcc00";
    ctx.fillStyle = "#ffcc00";
    ctx.fillRect(50,50,50,50);
}
window.onload = draw;
</script>
</head>
<body>
<canvas id="myCanvas" width="300" height="700"></canvas>
</body>
</html>

Note I also added a strokeStyle setting out of habit. In traditional paint programs, filling the rectangle without changing the stroke color would fill the whole canvas with orange.

2 Likes

diggy_dude, thank you that solved it!
D