如何在正确的位置绘制画布元素

How to draw canvas elements in the right positions?

本文关键字:布元素 元素 绘制 位置      更新时间:2023-09-26

我正在使用javascript在网站的DOM元素周围绘制一个矩形。

问题是矩形绘制在错误的位置。

我知道画布像真正的画布一样工作,所以你必须在填充画布之前"预绘制"所有内容,否则元素将按照您绘制它们的顺序彼此重叠。

这就是为什么我在循环之外定义画布和上下文。

这是我的代码:

    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    context.globalAlpha = 0.5;
    //Set canvas width/height
    canvas.style.width='100%';
    canvas.style.height='100%';
    //Set canvas drawing area width/height
    canvas.width = document.width;
    canvas.height = document.height;
    //Position canvas
    canvas.style.position='absolute';
    canvas.style.left=0;
    canvas.style.top=0;
    canvas.style.zIndex=100000;
    canvas.style.pointerEvents='none'; //Make sure you can click 'through' the canvas
    document.body.appendChild(canvas); //Append canvas to body element

var listingsRect = Array.prototype.map.call(document.querySelectorAll('.rc'), function(e) {
        return e.getBoundingClientRect();
    });
listingsRect.forEach(function(listingRect) {
    var x = listingRect.left;
    var y = listingRect.top;
    var width = listingRect.width;
    var height = listingRect.height;
    //Draw rectangle
    context.rect(x, y, width, height);
    context.fillStyle = 'yellow';
    context.fill();
});

但是,当我改变时 canvas.widthcanvas.height分别window.innerWidthwindow.innerHeight,然后画布在正确的位置绘制矩形,但它只在网站的可见区域绘制它们(显然)。

有人可以告诉我我的代码出了什么问题吗?

这是一个JS垃圾箱:

http://jsbin.com/elUToGO/1

context.rect(x,y,width,height) 中的 x,y 相对于 canvas 元素而不是浏览器窗口。

因此,如果您的画布元素绝对位于 50,75,并且您希望矩形位于窗口位置 110,125,您将像这样绘制矩形:

context.rect( 110-50, 125-75, width, height );

其他一些事情:

如果设置画布元素宽度/高度,然后绝对定位,则不需要 canvas.style.width/height。

文档宽度/高度已被弃用(在IE中不受支持)。请改用这个:

//Set canvas drawing area width/height
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

设置 style.left/top 时,您可能希望传递带有"px"的字符串,以防以后设置为>0。

canvas.style.left="0px";
canvas.style.top="0px";

.pointerEvents='none' 在大多数浏览器中都受支持(但在 IE<11 中不受支持)