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

查看:18
本文介绍了为什么我不能在我的 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 中,我在浅绿色线条的左侧看到了一条深绿色线条.为什么?我叫了stroke两次对吧?那么,为什么我的第一次中风会影响我的第二次呢?

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?

Here 是一个 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/

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

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