FreHu
FreHu

Reputation: 99

Strange behavior when drawing on multiple canvases

Basically, I'm trying to create a grid spanning multiple canvases, but I get strange behaviour on the first and last one. The stroke color and spacing is changed. I don't see how it could happen. Here is the relevant code, follow the link to see it in action. (the site is work in progress) http://www.gjar-po.sk/~hudak9c/test3/

var canvasCount = document.getElementsByTagName("canvas").length;

if (canvasCount > 0) {
  for (var i = 0; i < canvasCount; i++) {
    var canvas = document.getElementsByTagName("canvas")[i];

    if (canvas.getContext("2d")) {
      var can = canvas.getContext("2d");

      can.beginPath();

      for (var x = 5; x < 640; x += 20) {
        can.moveTo(x, 0);
        can.lineTo(x, canvas.height);
      }

      for (var y = 5; y < canvas.height; y += 20) {
        can.moveTo(0, y);
        can.lineTo(canvas.width, y);
      }

      can.lineWidth = 1;
      can.strokeStyle = "#000";
      can.stroke();
    } else {
      alert("getContext fail");      
    }
  }
}

Edit: I managed to fix the problem. It was caused by me (obviously) setting the width and height of the canvas through style.width and style.height, not through canvas.width and canvas.height, which made them stretch/shrink from their default dimensions instead of resize.

Upvotes: 1

Views: 108

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30453

Try to set width and height to the canvases by tag attributes width and height like this:

<canvas width="640" height="50">

Not by style attribute. It is very important. Because when you set style attribute and point there width and height properties, then your canvas with default real width and height just stretches to your new sizes.

Upvotes: 2

Related Questions