fips fips - 4 months ago 10
Javascript Question

How to draw an arbitrary shape using html canvas?

I'm trying to draw this chart-like shape on an html canvas:

0

100 .
.
200 . .
.
300 . .
.
400 . . .
.
500 .................................


I can't see anything wrong with my shape's co-ordinates:

(0, 500), (0, 400), (100, 400), (200, 300), (300, 200), (400, 100), (400, 500)


Html/js:

<html>
<head>
<script type="text/javascript">
function drawSteps(heights) {
var y = 500;
var steps = document.getElementById('steps').getContext('2d');
steps.fillStyle = '#C3EDBD';
steps.beginPath();
steps.moveTo(0, y);

var x = 0;
for (var i = 0; i < heights.length; i++) {
console.log(x.toString() + ', ' + (y - heights[i]).toString());
steps.lineTo(x, y - heights[i]);
x += 100;
}

steps.lineTo(x, 500);
steps.lineTo(0, 500);
steps.closePath();
steps.fill();
}
</script>
</head>
<body>
<canvas id="steps"></canvas>
<script type="text/javascript">
drawSteps([100, 100, 200, 300, 400]);
</script>
</body>
</html>


Nothing gets printed on the screen but canvas consumes a 300x150px placeholder.

rsp rsp
Answer

It is drawn but your canvas is too small so you don't see it.

Change your canvas to:

<canvas width=500 height=500 id="steps"></canvas>

and you'll see the result.

See DEMO.

Note that sizing it with CSS will not work because your canvas would still have the default of 300 x 150 pixels, but stretched to your dimensions shown in CSS.

See this demo to compare the HTML vs. CSS size of canvas.

Comments