claudiopb
claudiopb

Reputation: 1100

CANVAS - line with 100% of width

I would like to draw a line using CANVAS with 100% width acrossing through the entire screen similar to a css in the 'image-background' of the body like this example below:

Ex:

Made with CSS

body {
  background-image: url(horizontal-line.png);
  background-repeat: repeat-x;
  background-position: 0px 10%;
}

made with CANVAS

???

How can I solve it? Thank you

Upvotes: 1

Views: 1459

Answers (2)

Mulperi
Mulperi

Reputation: 1451

Updated demo: https://jsfiddle.net/mulperi/xnob50yd/1/ A full window sized canvas and 100% stroke in the middle of the screen

Here are the css and js parts:

<style>
  canvas {
    padding: 0;
    margin: auto;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
</style>
<canvas id="canvas"></canvas>
<script>
    const c = document.getElementById("canvas");
    const ctx = c.getContext("2d");

    c.width = window.innerWidth;
    c.height = window.innerHeight;

    ctx.fillStyle = "red";
    ctx.fillRect(0, window.innerHeight / 2, window.innerWidth, 10);
    ctx.fill();

    window.onresize = function() {
      ctx.width = window.innerWidth;
      ctx.height = window.innerHeight;
    }
</script>

With window.onresize you make sure that canvas changes size dynamically with the browser window.

Upvotes: 1

Persijn
Persijn

Reputation: 15000

Canvas <hr> line

Used javascript to find the width of the screen. document.documentElement.clientWidth
Then used that to set the size of the canvas element. canvas.width = screenWidth;
Then draw a rect width size 2px height and its width equal to screenWidth.
ctx.fillRect(0, 10, screenWidth, 2)
What is the 10 for? In this example i set the canvas to 20 height. So the middle of the canvas is 10.

document.addEventListener("DOMContentLoaded", function() {
  draw();
});

function draw() {
  var canvas = document.getElementById('demo');
  //Set the canvas to viewport size
  var screenWidth = document.documentElement.clientWidth;
  canvas.width = screenWidth;
  if (canvas.getContext) {
    var ctx = canvas.getContext('2d');

    ctx.fillStyle = 'rgb(255, 100, 0)';
    ctx.fillRect(0, 10, screenWidth, 2);

  } else {
    convas.addChild("No canvas here");
  }
}
body {
  margin: 0;
}


/*to make the canvas visible*/

#demo {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
}
<p>Canvas</p>
<canvas id="demo" width="" height="20"></canvas>

Upvotes: 0

Related Questions