本文介绍了HTML5画布-不同的笔触的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须用3条不同的线画一个图.线图.

I have to draw a graph with 3 different lines. A line graph.

我尝试这样做:

function draw()
{
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    ctx.lineWidth=10;

    ctx.strokeStyle="teal";
    ctx.moveTo(10,CompanyA[0]);
    ctx.lineTo(110,CompanyA[1]);
    ctx.lineTo(210,CompanyA[2]);
    ctx.stroke();


    ctx.strokeStyle="green";
    ctx.moveTo(10,CompanyB[0]);
    ctx.lineTo(110,CompanyB[1]);
    ctx.lineTo(210,CompanyB[2]);
    ctx.stroke();

    ctx.strokeStyle="yellow";
    ctx.moveTo(10,CompanyC[0]);
    ctx.lineTo(110,CompanyC[1]);
    ctx.lineTo(210,CompanyC[2]);
    ctx.stroke();
}

但是很显然,最后的笔画绘制了所有线条.所以我得到3条黄线,而不是蓝绿色,绿色和黄色.我尝试创建三个不同的上下文(ctx1,ctx2和ctx3),但是由于某些原因,所有这些都使用"ctx3.stroke()"调用绘制.

But apparently, the last stroke draws for all the lines. So I get 3 yellow lines, instead of a Teal, a Green and a Yellow one.I tried creating three different Context (ctx1, ctx2 and ctx3), but for some reason, all were drawn with the "ctx3.stroke()" call.

正确的方法是什么?

推荐答案

在每行之前添加ctx.beginPath()调用,并在每个ctx.stroke()

Add a ctx.beginPath() call before every line, and also a ctx.closePath() after every ctx.stroke()

如果不这样做,则每次调用stroke()方法时,不仅将绘制新行,而且还将绘制所有先前的行(使用新的strokeStyle),因为它是同一行路径仍然开放.

If you don't, every time you call the stroke() method, not only the new line will be drawn but also all the previous lines will be drawn again (with the new strokeStyle), since it's the same line path that is still open.

这篇关于HTML5画布-不同的笔触的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 05:50