Ad

On Mouseover Overlay Image Onto Canvas

- 1 answer

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.

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad