javascript - 如何在正确的位置绘制 Canvas 元素?

标签 javascript html canvas

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

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

我知道 Canvas 就像真正的 Canvas 一样工作,因此您必须在填充 Canvas 之前“预绘制”所有内容,否则元素将按照您绘制的顺序彼此重叠。

这就是我在循环之外定义 Canvas 和上下文的原因。

这是我的代码:

    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,然后canvas绘制矩形在正确的位置,但它只将它们绘制在网站的可见区域(显然)。

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

这是一个 JS bin:

http://jsbin.com/elUToGO/1

最佳答案

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

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

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

其他一些事情:

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

document.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 中不支持)

关于javascript - 如何在正确的位置绘制 Canvas 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19844995/

相关文章:

javascript - ag-grid Angular 1 onFilterModified事件如何获取参数

javascript - 在这种情况下如何修复自动关闭 div 标签

超出 Python tkinter Canvas root.after() 最大递归深度

javascript - 将 Canvas 缩放到鼠标光标

php - Mp4(通过使用 ffmpeg 连接两个 mp4 创建)不在 html5 视频标签中播放

javascript - 鼠标在 HTML Canvas 中移动时图像闪烁

javascript - 需要绕过 ExtJS 的异步特性

javascript - 这个 "invisible code"是如何工作的?

javascript - 如何查看最新版本的Electron使用的Chromium版本?

javascript - 带箭头按钮的 aria 角色选项卡