如何使用JavaScript在画布上绘制跑道 [英] How to draw a running track on a canvas with JavaScript
问题描述
我正在尝试使用JavaScript和HTML 5制作基本的曲目,如下图所示。
p>
有可能以编程方式执行此操作,还是应该使用图像来循环它?赛道的曲线将会改变。
我正在考虑使用PNG图像和 drawImage
来渲染画布。我不确定这是否是最好的方法。
最佳方法是什么?
我会使用贝塞尔曲线来绘制曲目。如果在飞行中绘制当前轨道段太慢,我会在一个大的隐藏画布中绘制整个轨道,并将其部分复制到可见画布上。
下面的代码片段会绘制一段看起来与您的示例差不多的片段。
window.onload = function(){var width = 314,height = 645,canvas = document.getElementById('trackCanvas'); canvas.width = width; canvas.height =高度; var context = canvas.getContext('2d'); context.strokeStyle ='#fff'; context.lineWidth = width / 2; context.beginPath(); context.moveTo(width / 2,1.1 * height); context.bezierCurveTo(width / 2.2,height / 2.5,width / 2.4,height / 4,width,0);
* {margin: 0;填充:0; box-sizing:border-box;}#trackContainer {display:inline-block;背景:#b2bfdc;}#trackCanvas {vertical-align:top;}
< div id =trackContainer> < canvas id =trackCanvas>< / canvas>< / div>
I am trying to make a basic track with JavaScript and HTML 5 like the image below.
Is it possible to do this programmatically or should I use an image to loop it? The curve of the track will be changing.
I'm thinking about using a PNG image and drawImage
to render the canvas. I'm not sure if that is the best way to do it.
What would be the optimal method?
I would use Bezier curves to draw the track. If drawing the current track segment on the fly is too slow, I would draw the whole track in a large hidden canvas and copy portions of it to the visible canvas.
The following snippet draws a segment that looks more or less like your example.
window.onload = function () {
var width = 314,
height = 645,
canvas = document.getElementById('trackCanvas');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.strokeStyle = '#fff';
context.lineWidth = width / 2;
context.beginPath();
context.moveTo(width / 2, 1.1 * height);
context.bezierCurveTo(width / 2.2, height / 2.5,
width / 2.4, height / 4,
width, 0);
context.stroke();
};
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#trackContainer {
display: inline-block;
background: #b2bfdc;
}
#trackCanvas {
vertical-align: top;
}
<div id="trackContainer">
<canvas id="trackCanvas"></canvas>
</div>
这篇关于如何使用JavaScript在画布上绘制跑道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!