[英]How to draw a running track on a canvas with JavaScript
I am trying to make a basic track with JavaScript and HTML 5 like the image below. 我正在尝试使用JavaScript和HTML 5进行基本跟踪,如下图所示。
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. 我正在考虑使用PNG图像和drawImage
渲染画布。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.