微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html5-canvas – 为什么我的HTML5画布中不能画出两行不同的颜色?

我试图使用 HTML5画布在绿线左边画一条红线.这是我的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中,我在绿色的绿线左边看到一条深绿色的线条.为什么?我打了两次中风?因此,为什么我的第一次中风会影响我的第二次?

Here一个JSfiddle,它说明了我的意思.

解决方法

你不是调用canvasContext.beginPath();当你开始绘制你的第二行.

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

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,100);
canvasContext.stroke();

// Draw the green line.
canvasContext.beginPath();
canvasContext.moveto(50,100);
canvasContext.stroke();

document.body.appendChild(canvas);

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

原文地址:https://www.jb51.cc/html5/168135.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。