我试图使用
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);