简体   繁体   中英

HTML5 Canvas Set Top/Left

I can easily set the canvas.width and canvas.height properties. I cannot find the right JavaScript syntax to set the offset of the canvas using top and left. I have tried setting these properties on the canvas directly and on the bounding rectangle.

I would like to be able to set the top and left offset so that I can reposition the canvas when a user clicks on a point.

If canvas.width = 600 works just fine; why doesn't canvas.top = 80 work? I am confused. Thx for your help.

请尝试canvas.style.top =“ 80px”;

In order to set the top position of the canvas, you need to wrap the canvas inside of another div with absolute positioning. Then set the position of the canvas to be relative to its wrapping div. Finally, you can set the style of the canvas.

Make sure you provide units eg px , em , rem , % , etc...

 var panel = document.getElementById('panel'); panel.width = 600; panel.height = 200; panel.style.top = '80px'; // Must specify unit. 
 .container { position: absolute; background: #0FF; } #panel { position: relative; background: #F00; } 
 <div class="container"> <canvas id="panel"></canvas> </div> 

The docs state:

The effect of top depends on how the element is positioned (ie, the value of the position property):

  • When position is set to absolute or fixed , the top property specifies the distance between the element's top edge and the top edge of its containing block. (Containing block needs to have property position: relative )
  • When position is set to relative , the top property specifies the distance the element's top edge is moved below its normal position.
  • When position is set to sticky , the top property behaves like its position is relative when the element is inside the viewport, and like its position is fixed when it is outside.
  • When position is set to static , the top property has no effect .

Make sure you have set position to relative or absolute. Have Look at the example below.

 <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;top: 80px; position: absolute;"> Your browser does not support the HTML5 canvas tag.</canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); ctx.moveTo(0, 0); ctx.lineTo(200, 100); ctx.stroke(); </script> </body> </html> 

In short, width and height are html attributes and can therefore be set using element.width and element.height . However, top is a css proberty, not an html attribute - therefore it can only be set using element.style.top .

Also, as already pointed out in the other answers, the css position proberty has to be either fixed or absolute in order for top and left to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM