0

我有这段代码可以让我像我想要的那样画一条水平线。问题是,当我在其中使用它时,它可以绘制,但是如果我拉伸浏览器窗口,线条会改变位置。我想这与它被包裹在右边的事实有关吗?我试图这样做,但它也没有奏效。我真的需要那些与布局对齐的线条。

<canvas id="myCanvas" width="1250" height="120"></canvas>

  <script>

    var canvas = $("#myCanvas")[0];
    var c = canvas.getContext("2d");
    var amount = 0;
    var startX = 164;
    var startY = 120;
    var endX = 1094;
    var endY = 120;

    setTimeout(function() {
    var interval = setInterval(function() {
        amount += 0.005; // change to alter duration
        if (amount > 1) {
            amount = 1;
            clearInterval(interval);
        }
        c.clearRect(0, 0, canvas.width, canvas.height);
        c.strokeStyle = "black";
        c.lineWidth=1;
        c.strokeStyle="#707070";
        c.moveTo(startX, startY);
        // lerp : a  + (b - a) * f
        c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
        c.stroke();
    }, 0);

}, 3000);

</script>
4

1 回答 1

3

调整画布大小时,画布绘图尺寸不会自动适应显示它的站点。你必须自己做。

我通常在我的画布抽屉初始化例程中做这样的事情:

this.canvas = canvas;
this.context = this.canvas.getContext("2d");
var _this = this;
var setDim = function() {
    _this.w = _this.canvas.clientWidth;
    _this.h = _this.canvas.clientHeight;
    _this.canvas.width = _this.w;
    _this.canvas.height = _this.h;
    _this.dimChanged = true;
    _this.draw();
};
setDim();
$(window).resize(setDim);
于 2012-09-27T15:49:29.257 回答