【问题标题】:On mouseover overlay image onto canvas在鼠标悬停时将图像叠加到画布上
【发布时间】:2016-04-29 18:12:23
【问题描述】:

https://jsfiddle.net/c309a2wo/

html

<canvas id="myCanvas" width="200" height="200"></canvas>

javascript

var canvas = document.getElementById("myCanvas");

var ctx = canvas.getContext('2d');

ctx.fillStyle = "rgb(0,255,255)";
ctx.fillRect(0, 0, canvas.width, canvas.height);

ctx.beginPath();
ctx.fillStyle = "rgb(200,0,0)";
ctx.arc(canvas.width/2, canvas.height/2, 50, 0, Math.PI*2);
ctx.fill();

我想在鼠标悬停在画布上时将图像(“close_icon.png”)叠加到右上角的画布上,并在鼠标离开画布时再次删除。

Jquery 可用,但我在 jsfiddle 中找不到添加它的选项。

可视化:

有没有一种简单的方法可以做到这一点?如果图像可以淡入淡出,则为布朗尼点。

【问题讨论】:

    标签: javascript jquery css canvas


    【解决方案1】:

    基本思想是将canvas 包装在容器元素中,然后在容器中添加仅在:hover 上显示的图像。

    var canvas = document.getElementById("myCanvas");
    
    var ctx = canvas.getContext('2d');
    
    ctx.fillStyle = "rgb(0,255,255)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.beginPath();
    ctx.fillStyle = "rgb(200,0,0)";
    ctx.arc(canvas.width/2, canvas.height/2, 50, 0, Math.PI*2);
    ctx.fill();
    div {
      position: relative;
        display: inline-block;
      }
    
      canvas {
        position: relative;
        z-index: -1;
      }
    
      img {
        position: absolute;
        top: 4%;
        right: 4%;
        opacity: 0;
        z-index: 2;
        -webkit-transition: opacity 0.4s linear;
        transition: opacity 0.4s linear;
      }
    
      div:hover img {
        opacity: 1;
      }
    <div>
    <canvas id="myCanvas" width="200" height="200"></canvas>
    <img src="http://placehold.it/30x30">
    </div>

    这里是working JSFiddle

    【讨论】:

    • 更新为淡入/淡出。
    • 谢谢。不希望添加额外的 div,但这是一个非常简洁的解决方案,所以我一定会使用它!
    【解决方案2】:

    将画布包裹在具有位置的外部容器中,然后您可以将图标放置在相对于外部包装器的任何位置

    HTML

    <div id="canvas-wrap">
        <span id="canvas-icon"></span>
        <canvas id="myCanvas" width="200" height="200"></canvas>
    </div>
    

    CSS

    #canvas-wrap{
        position:relative;
        width:200px; height:200px
    }
    #canvas-icon{
        background:yellow;
        width:32px;
        height:32px;
        position:absolute;
        top:10px;
        right:10px;
        z-index:10;
        display:none
    }
    #canvas-wrap:hover #canvas-icon{
        display:block
    }
    

    DEMO

    【讨论】:

      【解决方案3】:

      您可以使用.hover 添加&lt;span class="cross"&gt;

      $("#myCancas").hover(function(){$( this ).append( $( "<span class="cross"></span>" ) );});
      

      然后使用 CSS 设置样式:

      span.cross{
          display: block;
          width: 10px;
          height: 10px;
          background-image: url( path/to/cross/jpg);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 2014-08-20
        • 2018-05-18
        相关资源
        最近更新 更多