HTML5 Canvas - 不同的笔触 [英] HTML5 Canvas - Different Strokes

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

问题描述

我必须用 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.

这样做的正确方法是什么?

What would be the correct way to do this?

推荐答案

在每一行之前添加一个 ctx.beginPath() 调用,以及一个 ctx.closePath()> 在每个 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 Canvas - 不同的笔触的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆