0

I've got this chunk of code which allows me to draw a horizontal line just like I want. The problem is that when I use it in the it draws ok but if I stretch the browser window, the line changes position. I guess that has something to do with the fact that it's wrapped inside a right? I tried to do that but it didn't work either. I really need those lines aligned with the layout.

<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> 

1 Answer 1

3

When the canvas is resized, the canvas drawing dimensions aren't automatically adapted to the site in which it is displayed. You must do it yourself.

I usually do something like this in my canvas drawer initialization routines :

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.