Reputation: 468
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.
Upvotes: 1
Views: 8703
Reputation: 73
CSS
canvas{
position: absolute;
top: 80px;
}
JS
const canvas = document.querySelector("canvas");
canvas.style.position = "absolute";
canvas.style.top = "80";
Upvotes: -1
Reputation: 1078
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.
Upvotes: 0
Reputation: 316
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>
Upvotes: 1
Reputation: 48620
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 e.g. 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 (i.e., the value of theposition
property):
- When
position
is set toabsolute
orfixed
, thetop
property specifies the distance between the element's top edge and the top edge of its containing block. (Containing block needs to have propertyposition: relative
)- When
position
is set torelative
, thetop
property specifies the distance the element's top edge is moved below its normal position.- When
position
is set tosticky
, thetop
property behaves like itsposition
isrelative
when the element is inside the viewport, and like itsposition
isfixed
when it is outside.- When
position
is set tostatic
, thetop
property has no effect.
Upvotes: 2