我有这段代码可以让我像我想要的那样画一条水平线。问题是当我在它中使用它时绘制正确但如果我拉伸浏览器窗口,该行改变位置。我想这与它被包裹在右边的事实有关?我试图这样做,但它也没有用。我真的需要那些与布局对齐的线条。
<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>
答案 0 :(得分: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);