【问题标题】:draw circles on every span element在每个 span 元素上绘制圆圈
【发布时间】:2011-12-31 06:20:14
【问题描述】:

我想在我给了 span 元素的字符上画圆圈。我已经让它与一个元素一起工作(见注释代码)。我只想通过每个跨度元素来做到这一点。 首先,我首先尝试悬停,但我已经失败了。就悬停而言,它应该在调用函数 draw get 时发生。

function draw() {  
    ctx.save();
    ctx.translate(plotX1, 0);

    $("p").find("span").hover(function(){

            console.log("hover");
            var x = $(this).offsetLeft;
            var y = $(this).offsetTop;
            y += $(this).offsetHeight;
            ellipse(ctx, x, y, 10);
            ctx.strokeStyle = "rgba(200, 0, 0, 50)";
            ctx.stroke();   
    });


    ctx.restore();

    /*
// this worked on the element with id s2
    var x = s2.offsetLeft;
    var y = s2.offsetTop;
    y += s2.offsetHeight;
    ctx.fillStyle = "rgb(0, 250, 0)";
    //ctx.fillRect(x, y, 10, 10);
    ellipse(ctx, x, y, 10);
    ctx.strokeStyle = "rgba(200, 0, 0, 50)";
    ctx.stroke();
    */

}  

【问题讨论】:

    标签: javascript jquery html html5-canvas


    【解决方案1】:

    example jsfiddle

    这至少更接近您正在寻找的东西,悬停的工作,它绘制圆圈,但它也连接圆圈,应该能够轻松解决这个问题(也许ctx.moveTo()

    function draw() {
        $('#canv').attr('width', $('p').width()).attr('height', $('p').height());
    
        //ctx.translate(plotX1, 0);
        $('p span').hover(function() {
            ctx.save();
    
            var x = this.offsetLeft,
                y = this.offsetTop;
            y += this.offsetHeight / 2;
    
            //ctx.moveTo(x, y);
    
            ellipse(ctx, x, y, 10);
    
            ctx.strokeStyle = "rgba(200, 0, 0, 50)";
            ctx.stroke();
    
            ctx.restore();
        }, function() {
            clearCanvas(ctx);
        });
    }
    

    我认为主要问题可能是您使用$(this).offsetLeft; 获取偏移量的位置(其中$(this) 是一个jQuery 对象)。 this.offsetLeft 工作。


    想了想:

    不确定您的最终目标是什么,但您也可以使用 CSS 围绕 span 做一个简单的box-shadow

    example jsfiddle

    p span:hover {box-shadow:0 0 0 2px #f00;border-radius:10px;}
    

    【讨论】:

    • 用你的代码我什么也看不到。也许是因为画布在整个页面上(我也无法选择文本)。画布在整个页面上必须保持这种状态。这条线是干什么用的? $('#canv').attr('width', $('p').width()).attr('height', $('p').height());
    • $('#canv').attr('width', $('p').width()).attr('height', $('p').height()); 将画布大小设置为与段落相同的大小。我没有看到您所看到的内容,使用 Chrome 会显示圆圈,我可以选择文本。在 Firefox 中获得不同的结果,可以选择文本,但当我将鼠标悬停在它们上时,跨度上只显示一个圆圈。
    • 我将 x 和 y 记录到控制台,x 未定义,y 是 nan。
    猜你喜欢
    • 2022-01-20
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多