How would I code: When mouse enters predefined area in canvas, image appears (already sorted the image), when exiting said predefined area, it disappears again.
This is all using jQuery.
Thanks in advance.
jQuery will track hover/blur on the canvas element, but not on individual drawings inside the canvas. Images drawn on html canvas are not DOM elements. Instead they are like forgotten painted pixels on a canvas.
These are the steps to apply a hover-effect to an image draw inside your canvas:
Keep track of your image's definition (x,y,width,height) in a javascript object,
Listen for mousemove events on the canvas,
Test if the mouse is inside your image,
When the mouse enters or leaves your circle, redraw or clear your image.
To make your hover/blur more efficient, keep track of the previous image status (visible/not visible) and don't do anything if it hasn't changed status.
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
var lastMouseWasIn;
var currentMouseIsIn=false;
var imgDef={x:30,y:30};
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolSmall.png";
function start(){
imgDef.width=img.width;
imgDef.height=img.height;
draw();
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}
function draw(){
if(lastMouseWasIn===currentMouseIsIn){return;}
ctx.clearRect(0,0,cw,ch);
if(currentMouseIsIn){
ctx.drawImage(img,imgDef.x,imgDef.y);
}
ctx.strokeRect(imgDef.x,imgDef.y,imgDef.width,imgDef.height);
}
function handleMouseMove(e){
e.preventDefault();
e.stopPropagation();
x=parseInt(e.clientX-offsetX);
y=parseInt(e.clientY-offsetY);
currentMouseIsIn = x>imgDef.x
&& x<imgDef.x+imgDef.width
&& y>imgDef.y
&& y<imgDef.y+imgDef.height;
draw();
lastMouseWasIn=currentMouseIsIn;
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Move mouse in and out of rectangle to show/hide image.</h4>
<canvas id="canvas" width=300 height=300></canvas>