AndrewB
AndrewB

Reputation: 836

On mouseover overlay image onto canvas

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();

I would like to overlay an image("close_icon.png") onto a canvas in the top right corner when the mouse hovers over the canvas, and is removed again when the mouse leaves the canvas.

Jquery is available, though I couldn't find the option to add it in jsfiddle.

Visualisation:

Current

Desired

Is there an easy way to accomplish this? Brownie points if the image can fade-in and out.

Upvotes: 0

Views: 1753

Answers (3)

charlietfl
charlietfl

Reputation: 171690

Wrap canvas it in outer container that has position, then you can position the icon wherever you want relative to the outer wrapper

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

Upvotes: 1

Brett DeWoody
Brett DeWoody

Reputation: 62871

The basic idea is to wrap your canvas in a container element, then add an image in the container that is only shown on :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>

Here'a working JSFiddle.

Upvotes: 4

Peyman Mohamadpour
Peyman Mohamadpour

Reputation: 17964

You may add the <span class="cross"> using .hover:

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

and then style it, using CSS:

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

Upvotes: 0

Related Questions