如何在正确的位置绘制画布元素
How to draw canvas elements in the right positions?
我正在使用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.width
和canvas.height
分别window.innerWidth
和window.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 中不受支持)
相关文章:
- CKEditor Widget-阻止编辑可编辑元素本身
- 如何设置html元素填充的动画
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 使用clickToggle并在单击另一个元素时关闭元素
- 单击时将焦点更改为元素
- 表追加而不附加最后一个元素
- 如何在jQuery中获取元素的形式
- 我可以获得相对于被点击元素的确切点击位置吗
- 在函数中添加数组元素的数值
- 在单击任何位置时隐藏元素,而不检查每次DOM单击
- 将视口底部滚动到元素底部
- 是否有任何snippet或jQuery插件可以列出easylist.txt模式匹配的DOM中的所有元素
- 在不使用JQuery的情况下隐藏DOM中的选定元素
- 如何使用jquery处理php循环通过元素
- 在 jquery 可排序后定义
- 元素
- 元素的索引
- 元素
- “<元素/>”到“<元素> 元素>”是否有效
- d3.js:水平居中
元素的父元素'元素 - Polymer 1.0不能访问嵌套模板中的元素.元素
- 为什么是n't '元素a
元素