How can I draw a diagonal line in that lo

2019-09-05 19:35发布

问题:

In browsers that support HTML5, this code draws a diagonal line:

<!DOCTYPE html><html><body><script>
var canvas = document.createElement('canvas');
canvas.width = 100;
canvas.height = 100;
var ctx = canvas.getContext('2d');
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.lineWidth = 1;
ctx.stroke();
document.body.appendChild(canvas);
</script></body></html>

However, the rendering looks drastically different in Safari:

(Chrome 49.0, Firefox 45.0, Safari 9.0 from left to right.)

I.e., in Safari, the line looks about twice as thick as the others.

Can I do anything to make the line look identical in all three browsers?

回答1:

The difference is caused by the different ways that browsers anti-alias your line.

You can't over-ride or turn off anti-aliasing on the canvas element so you're stuck with the different line renderings across browsers.

The only sure workaround is to draw your own line pixel-by-pixel. You can use Bresenham's line algorithm to create your line.

Here's example code and a Demo:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imgData.data;

bresnehamLine(25,25, 250, 125);
ctx.putImageData(imgData, 0, 0);


function setPixel(x, y) {
  var n = (y * canvas.width + x) * 4;
  data[n] = 0;
  data[n + 1] = 0;
  data[n + 2] = 255;
  data[n + 3] = 255;
}

// Attribution: https://www.cs.helsinki.fi/group/goa/mallinnus/lines/bresenh.html
function bresnehamLine(x0, y0, x1, y1) {
  var dx = Math.abs(x1 - x0),
      sx = x0 < x1 ? 1 : -1;
  var dy = Math.abs(y1 - y0),
      sy = y0 < y1 ? 1 : -1;
  var err = (dx > dy ? dx : -dy) / 2;
  while (true) {
    var n = (y0*canvas.width+x0)*4;
    data[n] = 0;
    data[n + 1] = 0;
    data[n + 2] = 255;
    data[n + 3] = 255;
    if (x0 === x1 && y0 === y1) break;
    var e2 = err;
    if (e2 > -dx) {
      err -= dy;
      x0 += sx;
    }
    if (e2 < dy) {
      err += dx;
      y0 += sy;
    }
  }
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>