Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas drawing multicolored lines

I am trying to draw two parallel lines on the canvas, but it seems like properties of the latter overwrites the former. Please suggest what could be wrong :

<html>
<head>
<script type="application/javascript">
  function draw() {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    // draw a 10 pix green line
    ctx.strokeStyle='#00cc00';
    ctx.lineWidth=10;
    ctx.moveTo(100,0);
    ctx.lineTo(100,1000);
    ctx.stroke();
    // draw a 20 pix red line
    ctx.strokeStyle='#cc0000';
    ctx.lineWidth=20;
    ctx.moveTo(140,0);
    ctx.lineTo(140,1000);
    ctx.stroke();
  }
  </script>
  </head>
  <body onload="draw()">
    <div><canvas id="canvas" width="1000" height="1000"></canvas></div>
  </body>
  </html>
like image 674
Amarsh Avatar asked Aug 29 '10 12:08

Amarsh


People also ask

How do you change the color of the lines on a canvas?

To set the color of an HTML5 Canvas line, we can use the strokeStyle property of the canvas context, which can be set to a color string such as red, green, or blue, a hex value such as #FF0000 or #555, or an RGB value such as rgb(255, 0, 0).

Is HTML5 canvas still used?

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.

How do I style a canvas in HTML?

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content. Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.

Can you draw lines on canvas?

To draw a line on a canvas, you use the following steps: First, create a new line by calling the beginPath() method. Second, move the drawing cursor to the point (x,y) without drawing a line by calling the moveTo(x, y) . Finally, draw a line from the previous point to the point (x,y) by calling the lineTo(x,y) method.


1 Answers

Call ctx.beginPath before drawing each line. When the strong stroke call is made, the first line is still part of the current path so it gets drawn again in the new color.

like image 172
Matti Virkkunen Avatar answered Sep 19 '22 05:09

Matti Virkkunen