[英]How to draw an arbitrary shape using html canvas?
I'm trying to draw this chart-like shape on an html canvas: 我正在尝试在html画布上绘制类似于图表的形状:
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 / 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. 屏幕上没有任何内容打印出来,但是画布占用了300x150px的占位符。
It is drawn but your canvas is too small so you don't see it (300 x 150 pixels by default). 它已绘制,但是您的画布太小,因此您看不到它(默认为300 x 150像素)。
Change your canvas to: 将画布更改为:
<canvas width=500 height=500 id="steps"></canvas>
and you'll see the result. 您会看到结果。
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 defined in CSS. 请注意,使用CSS调整大小将无法使用,因为您的画布仍将具有默认的300 x 150像素,但会拉伸到CSS中定义的尺寸。
See this demo to compare the HTML vs. CSS size of canvas. 查看此演示以比较HTML和CSS画布大小。
You just need to define a width and height for your canvas 您只需要为画布定义宽度和高度
<canvas id="steps" width="1000" height="1000"></canvas>
It's probably better to do this with CSS, but this is a quick fix for your problem 使用CSS这样做可能更好,但这是针对您问题的快速解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.