我有一个简化的风图(有关它的外观,请参见https://earth.nullschool.net/)。
我每10毫秒对该点进行加权插值,然后创建一个uVector和vVector,然后计算该速度。基于该速度,如下将相应的颜色分配给该点。
if (weightWS < 13) {
color = "#ffa500"
}
if (weightWS < 10) {
color = "#CCCC00"
}
if (weightWS < 7) {
color = "#008000"
}
if (weightWS < 4) {
color = "#0000ff"
}
if (weightWS < 1) {
color = "#800080"
}
然后将颜色发送到动画功能。它在drawData[3]
。
function animate(){
//This changes the opacity of the canvas
ctx.beginPath();
ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.closePath();
//This is where the point is created.
for(var pointCount=0;pointCount<pointNum;pointCount++){
let xMid,yMid;
let xPoint = points[pointCount][0];
let yPoint = points[pointCount][1];
if(xPoint < 141 || xPoint >580 || yPoint < 120 || yPoint > 524){
xPoint = getRandomIntInclusive(141,580);
yPoint = getRandomIntInclusive(120,524);
points.push([xPoint,yPoint]);
}
//ctx.fillStyle = "#000000";
var drawData = weightAllData(xPoint,yPoint); //output: speed, uVec, vVec, color
colorArr[pointCount] = drawData[3]; //assign color to array, for QA purposes
ctx.moveTo(xPoint, yPoint);
ctx.lineTo(xPoint+drawData[1],yPoint+drawData[2]);
ctx.strokeStyle = drawData[3]; //assign the color to the strokeStyle
//console.log(ctx.strokeStyle); //prints color
ctx.stroke(); //makes line.
points[pointCount][0] = xPoint+drawData[1];
points[pointCount][1] = yPoint+drawData[2];
//console.log(drawData[0])
}
尽管控制台显示不同的颜色(主要是"#800080"
和)"#0000ff"
,但是颜色会影响所有点,速度为1+的点仍然具有紫色("#800080"
)。
颜色一次只能影响一个像素,我很肯定"#0000ff"
应该显示一些蓝点()。如果显示蓝点,则一次是所有像素,这不是目标。
无论动画的速度如何(例如10ms,1000ms,10000ms),都会发生这种情况。是否有人对问题出在哪里有任何解决方案或暗示?
非常感谢您的所有帮助。我非常感谢您所花费的时间和精力。
问题是在for循环中,您要将路径段添加到同一路径。
例如,以下代码段具有两个循环。第一个将100个路径段添加到一个路径。每次stroke()
调用时都会重画所有线条。所有路径段均以最后使用的颜色绘制。也是非常低效的,顶部循环最终绘制5050个线段,第一遍绘制1条线,第二遍绘制另外2条,第三遍绘制3条(第三遍已经绘制6条线),依此类推。
第二个循环在循环内开始一条新路径,每个路径段都有不同的颜色,并且只绘制了100条线段。
const ctx = canvas.getContext("2d");
ctx.lineWidth = 2;
const colors = ["Green", "Blue", "Red", "Black", "Yellow"];
ctx.beginPath(); // start a new path
for (let i = 0; i < 100; i ++) {
ctx.strokeStyle = colors[i % colors.length];
ctx.moveTo(i * 5, 0); // adds to existing path
ctx.lineTo(i * 5, 40);
ctx.stroke(); // draw all path segments since last beginPath
}
for (let i = 0; i < 100; i ++) {
ctx.strokeStyle = colors[i % colors.length];
ctx.beginPath(); // start a new path
ctx.moveTo(i * 5, 60); // adds to the path
ctx.lineTo(i * 5, 100);
ctx.stroke(); // draw the path
}
canvas {boarder: 2px solid #000}
<canvas id="canvas" width="500" height="100"></canvas>
通常,每当您更改样式,线宽等时,都需要开始新的路径。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句