为什么我不能在HTML5画布上绘制两行不同颜色的线? [英] Why can't I draw two lines of varying colors in my HTML5 canvas?

查看:151
本文介绍了为什么我不能在HTML5画布上绘制两行不同颜色的线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用HTML5画布在绿线的左侧绘制一条红线.这是我的JavaScript:

I am trying to use HTML5 canvas to draw a red line to the left of a green line. Here is my javascript:

var canvas = document.createElement('canvas');
canvas.height = 150;
canvas.width = 150;
var canvasContext = canvas.getContext('2d');
canvasContext.beginPath();

// Draw the red line.
canvasContext.strokeStyle = '#f00';
canvasContext.moveTo(10, 0);
canvasContext.lineTo(10, 100);
canvasContext.stroke();

// Draw the green line.
canvasContext.moveTo(50, 0);
canvasContext.strokeStyle = '#0f0';
canvasContext.lineTo(50, 100);
canvasContext.stroke();

document.body.appendChild(canvas);​

但是,在Google Chrome浏览器中,我在浅绿色线的左侧显示了一条深绿色的线.为什么?我叫过两次中风对不对?因此,为什么我的第一次中风会影响我的第二次中风?

However, in Google Chrome, I get a dark green line to the left of a light green line. Why? I called stroke twice right? Hence, why should my first stroke affect my second one?

此处是一个JSFiddle,它说明了我的意思.

Here is a JSFiddle that illustrates what I mean.

推荐答案

开始绘制第二条线时不会调用canvasContext.beginPath();.

You aren't calling canvasContext.beginPath(); when you start drawing your second line.

为了使绘图部分更加独立,我添加了空格:

To make the drawing sections more independent, I added whitespace:

var canvas = document.createElement('canvas');
canvas.height = 150;
canvas.width = 150;

var canvasContext = canvas.getContext('2d');

// Draw the red line.
canvasContext.beginPath();
canvasContext.strokeStyle = '#f00';
canvasContext.moveTo(10, 0);
canvasContext.lineTo(10, 100);
canvasContext.stroke();

// Draw the green line.
canvasContext.beginPath();
canvasContext.moveTo(50, 0);
canvasContext.strokeStyle = '#0f0';
canvasContext.lineTo(50, 100);
canvasContext.stroke();

document.body.appendChild(canvas); 

演示: http://jsfiddle.net/AhdJr/2/

Demo: http://jsfiddle.net/AhdJr/2/

这篇关于为什么我不能在HTML5画布上绘制两行不同颜色的线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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