3

是否可以使用 jQuery 引用在 HTML5 画布元素上绘制的图形?这是我为 EaselJS 编写的一个函数,它遍历一个包含矢量坐标数组的对象:

function newShape(obj,shape,coords){
    obj.graphics.beginFill('green');
    obj.alpha = 0.05;
    for (var i=0; i<coords[shape].length; i+=2) {
        var arr = coords[shape].slice(i,i+2);
        obj.graphics.lineTo(arr[0],arr[1]);
    }
    obj.graphics.closePath();
    obj.graphics.endFill();
    stage.addChild(obj);
}

坐标对象看起来像这样,有 100 个点:

var coords = {};

coords['0']  = [214,266,214,291,194,291];
coords['1']  = [243,1,254,2,278,9,290,14];
coords['2']  = [109,112,116,114,129,117];

和舞台:

canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);

shape1 = new createjs.Shape();
shape2 = new createjs.Shape();
shape3 = new createjs.Shape();

newShape(shape1,'shape1',coords);
newShape(shape2,'shape2',coords);
newShape(shape3,'shape3',coords);

我可以为点击/触摸事件添加侦听器到渲染的形状,但是我希望能够将每个图形作为 DOM 元素引用,以便与 Bootstrap Popover 和 niceScroll 等插件一起使用,例如$(shape1).popover('show');...... 我一直在积极研究一个没有成功的解决方案,任何帮助将不胜感激!

4

1 回答 1

1

选项1 :

从 Shmiddty 的帖子中,一种使用 2d 上下文引用的编程方法:

function Shape(can) {
    this.x = 0;
    this.y = 0;
    this.width = 0;
    this.height = 0;
    this.fill = "rgba(0,0,0,0)";
    this.parent = can;

    this.draw = function(ctx) {
        if (!$(me.parent).is(':visible')) return;

        var parts = me.fill.split(',');
        parts[3] = $(me.parent).css("opacity") + ')';
        me.fill = parts.join(',');

        ctx.fillStyle = me.fill;
        ctx.fillRect(me.x, me.y, me.width, me.height);
    };

    var me = this;
}

(function() {
    var can = $("#sandbox")[0],
        ctx = can.getContext('2d'),
        wid = can.width,
        hei = can.height,
        sha = new Shape($('<div id="box"/>').appendTo('body'));

    sha.x = 0;
    sha.y = 0;
    sha.width = 50;    
    sha.height = 50;
    sha.offsetWidth = 50;
    sha.offsetHeight = 50;
    sha.fill = "rgba(000,111,222,1)";

    (function draw(){
        ctx.clearRect(0,0,wid,hei);
        sha.draw(ctx);
        webkitRequestAnimationFrame(draw);
    })();


    $(can).click(function(){
        $(sha.parent).fadeToggle();
    });
    $('#box').click(function(){
        $(this).fadeToggle();
    });
})();​  

选项 2:

I was able to track x,y coords from click and touch events by applying CSS to a hidden DOM element.

Calling a bootstrap popover :

$("#canvas").click(function(e) {
    var x = e.pageX;
    var y = e.pageY;

    if ($.inArray(x, coords['shape1']) !== -1 || $.inArray(y, coords['shape1']) !== -1){
        $("#myObj").css({'position':'absolute','top':y,'left':x}).popover({
            trigger: 'click',
            placement:'top',
        }).popover('show');
    }
});
stage.update();

HTML:

<canvas id="canvas" width="375" height="322"></canvas>
<span class="myObj" data-content="lorem ipsum content" data-original-title="pop-title"></span>
于 2012-11-16T02:19:18.030 回答