Dmi*_*rin 4 javascript google-chrome-extension imgur html5-canvas
我需要在 Javascript 中实现从选定区域获取元素。这是在 chrome 应用程序中制作更好的、类似桌面的 UI 所必需的。最近的例子是在 Imgur 扩展中选择区域:
所以问题是:
我发现这很有趣,所以我从头开始做了一些东西,使用 jQuery 因为否则它会变得太复杂:http : //jsfiddle.net/EuSBU/1/。
我希望它足够直截了当,请询问您是否有想知道的事情。
它基本上归结为检查每个元素是否被矩形封装。
$("#start_select").click(function() {
$("#select_canvas").show();
});
$('*').bind('selectstart', false);
var start = null;
var ctx = $("#select_canvas").get(0).getContext('2d');
ctx.globalAlpha = 0.5;
$("#select_canvas").mousedown(function(e) {
start = [e.offsetX, e.offsetY];
}).mouseup(function(e) {
end = [e.offsetX, e.offsetY];
var x1 = Math.min(start[0], end[0]),
x2 = Math.max(start[0], end[0]),
y1 = Math.min(start[1], end[1]),
y2 = Math.max(start[1], end[1]);
var grabbed = [];
$('*').each(function() {
if(!$(this).is(":visible")) return;
var o = $(this).offset(),
x = o.left,
y = o.top,
w = $(this).width(),
h = $(this).height();
if(x > x1 && x + w < x2 && y > y1 && y + h < y2) {
grabbed.push(this);
}
});
console.log(grabbed);
start = null;
$(this).hide();
}).mousemove(function(e) {
if(!start) return;
ctx.clearRect(0, 0, this.offsetWidth, this.offsetHeight);
ctx.beginPath();
var x = e.offsetX,
y = e.offsetY;
ctx.rect(start[0], start[1], x - start[0], y - start[1]);
ctx.fill();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4992 次 |
| 最近记录: |