简体   繁体   中英

Position of html canvas on web page

I have a canvas based script similar to dottydots . Its working fine but i want to change its canvas position. I tried this position:absolute. It works but it only move canvas`s visual area. I mean the working area of canvas is (where we use mouse pointer to do something on canvas) remain at old position.

I guess you have issues retrieving the right mouse coordinates.
You have to use getBoundingClientRect to have them right.

So, provided you are not using with/height in css to scale the canvas, the formula will be :

var mousePos   = [-1, -1];
var canvasRect, canvasLeft, canvasTop
function updateCanvasRect() {
    canvasRect = canvas.getBoundingClientRect();
    canvasLeft = canvasRect.left;
    canvasTop  = canvasRect.top ;
}
function updateMousePos(e) {
   mousePos[0] = e.clientX - canvasLeft;
   mousePos[1] = e.clientY - canvasTop ;
}

you must call

updateCanvasRect

after document loaded, and then on scroll if you allow scroll.

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