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>
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With