How to move rectangle on canvas - javascript

I use canvas in my application using JavaScript. On that canvas I draw one rectangle. I want to move rectangle with the help of mouse (e.g moving slider) how to move that rectangle using JavaScript or jQuery.

A Canvas is literally just a surface that you paint on and none of the things you paint are objects.
If you want to pretend they are objects (like moving around a rectangle or a line) then you need to keep track of everything and do all the hit-testing and re-painting yourself .
I wrote a gentle introduction article on getting started by making rectangles that you can select and drag around. Give that a read.

On a second reading, I think I misunderstood your question, so here's an updated version:
http://jsfiddle.net/HSMfR/4/
$(function () {
var
$canvas = $('#canvas'),
ctx = $canvas[0].getContext('2d'),
offset = $canvas.offset(),
draw,
handle;
handle = {
color: '#666',
dim: { w: 20, h: canvas.height },
pos: { x: 0, y: 0 }
};
$canvas.on({
'mousedown.slider': function (evt) {
var grabOffset = {
x: evt.pageX - offset.left - handle.pos.x,
y: evt.pageY - offset.top - handle.pos.y
};
// simple hit test
if ( grabOffset.x >= 0
&& grabOffset.x <= handle.dim.w
&& grabOffset.y >= 0
&& grabOffset.x <= handle.dim.h
) {
$(document).on({
'mousemove.slider': function (evt) {
handle.pos.x = evt.pageX - offset.left - grabOffset.x;
// prevent dragging out of canvas
if (handle.pos.x < 0) {
handle.pos.x = 0;
}
if (handle.pos.x + handle.dim.w > canvas.width) {
handle.pos.x = canvas.width - handle.dim.w;
}
//handle.pos.y = evt.pageY - offset.top - grabOffset.y;
},
'mouseup.slider': function () {
$(document).off('.slider');
}
});
}
}
});
draw = function() {
var val = (100 * (handle.pos.x / (canvas.width - handle.dim.w))).toFixed(2) + '%';
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillStyle = handle.color;
ctx.fillRect(handle.pos.x, handle.pos.y, handle.dim.w, handle.dim.h);
ctx.textBaseline = 'hanging';
ctx.font = '12px Verdana';
ctx.fillStyle = '#333';
ctx.fillText(val, 4, 4);
ctx.fillStyle = '#fff';
ctx.fillText(val, 3, 3);
};
setInterval(draw, 16);
});
prev version:
Very simple solution to extend upon:
http://jsfiddle.net/HSMfR/
$(function () {
var
ctx = $('#canvas')[0].getContext('2d'),
$pos = $('#pos'),
draw;
draw = function() {
var x = ($pos.val() / 100) * (ctx.canvas.width - 20);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillStyle = 'black';
ctx.fillRect(x, 0, 20, 20);
};
setInterval(draw, 40);
});

Related

Animating circle in html canvas with javascript

I need to animate a circle moving in a html canvas. For this purpose, I decided to use a typical sprite animation technique which consist in the following general steps:
Initialize the background (in this case, just a gray rectangle)
Calculate new sprite's coordinates
Draw the sprite (the circle)
Reset the backgound
Goto 2
My problem is that the result looks like all the old circles seem to be redrawn each time I call ctx.fill() despite I am reseting the canvas.
What am I doing wrong? Any suggestion?
var canvas;
var ctx;
var canvasPos;
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
function init() {
canvas = document.getElementById("target_temp");
ctx = canvas.getContext("2d");
canvasPos = { x: canvas.offsetLeft, y: canvas.offsetTop };
drawSlider();
}
var y = 7;
function animate() {
y = y + 1;
knob.setPosition(8, y);
knob.clear();
knob.draw();
if (y < 93) {
setTimeout(animate, 10);
}
}
function drawSlider() {
ctx = canvas.getContext("2d");
ctx.fillStyle = "#d3d3d3";
ctx.fillRect(0, 0, 16, 100);
}
var knob = {
position: { x: 8, y: 7 },
oldPosition: { x: 8, y: 7 },
setPosition(_x, _y) {
this.oldPosition = this.position;
this.position.x = _x;
this.position.y = _y
},
clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSlider();
},
draw() {
ctx.fillStyle = rgbToHex(0, 0, 112);
ctx.arc(8, this.position.y, 7, 0, 2 * Math.PI);
ctx.fill();
}
}
window.onload = function () { init(); animate(); };
<!DOCTYPE html>
<html>
<boyd>
<canvas id="target_temp" width="16px" height="100px"></canvas>
</boyd>
</html>
I see you already figured out to use the beginPath but I will disagree with the location I will put that at the very beginning of the function animate, take a look at the code below, I refactored your code, got rid of some unused variables, and made the slider an object just like you have for the knob
var canvas = document.getElementById("target_temp");
var ctx = canvas.getContext("2d");
var slider = {
width: 16,
height: 100,
draw() {
ctx.fillStyle = "#d3d3d3";
ctx.fillRect(0, 0, this.width, this.height);
}
}
var knob = {
position: {x: 8, y: 7},
radius: 8,
draw() {
ctx.fillStyle = "#00D";
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.fill();
}
}
function animate() {
ctx.beginPath()
ctx.clearRect(0, 0, canvas.width, canvas.height);
slider.draw();
if (knob.position.y + knob.radius < slider.height)
knob.position.y++;
knob.draw();
setTimeout(animate, 10);
}
window.onload = function() {
animate()
};
<canvas id="target_temp"></canvas>
Ok, I found the cause: the arc() method stacks the circle as part of the path, so, for it to work, we need to reset the path like this:
draw() {
ctx.fillStyle = rgbToHex(0, 2*y, 107);
ctx.beginPath();
ctx.arc(8, this.position.y, 7, 0, 2 * Math.PI);
ctx.fill();
}

Animation stops after mousemove (canvas)

I created a script that makes a canvas circle follow the mouse when is X is bigger.However as you can see it only works during the mouse move. when the mouse stops I couldn't find a way to make the circle move. Plus, did i use the correct logic for making this code?
Heres a snippet:
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
var PI = Math.PI;
window.requestAnimFrame = (function(){
return window.requestAnimationFrame || // La forme standardisée
window.webkitRequestAnimationFrame || // Pour Chrome et Safari
window.mozRequestAnimationFrame || // Pour Firefox
window.oRequestAnimationFrame || // Pour Opera
window.msRequestAnimationFrame || // Pour Internet Explorer
function(callback){ // Pour les élèves du dernier rang
window.setTimeout(callback, 1000 / 60);
};
})();
function pos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function elm_fixe() {
ctx.fillStyle = "rgba(050, 155, 255, 1)";
ctx.fillRect(0, 0, 30, 30, 1);
for (var x = 0, y = 0, alpha = 1; alpha >= 0; alpha -= 0.1, x += 40) {
ctx.fillStyle = "rgba(050, 155, 255, " + alpha + ")";
ctx.fillRect(x, 0, 30, 30);
}
}
function cercle(x, y) {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(x, y, 30, 0, PI * 2, true);
ctx.fill();
}
var x = 250,
y = 250;
function bouger(e) {
console.log(e.clientX)
if ( pos(canvas, e).x > x) {
x += 1;
};
}
function draw(e) {
ctx.clearRect(0, 0, 800, 500);
bouger(e);
cercle(x, y);
elm_fixe();
}
/* window.requestAnimFrame(function() {
canvas.addEventListener('mousemove', function(e) {
window.requestAnimFrame(function() { draw(e) });
});
}
);
*/
window.addEventListener('mousemove', function(e) {
draw(e);
});
<canvas height="500" width="800" id="canvas"></canvas>
First of all, when experimenting with this it's important to focus on getting the task at hand done, so I removed your fixed drawn elements, as that's easy.
The main issue you are having is that you only update onmousemove, which could get in your way. The best thing to do is simply to store the mouse coordinates in a separate object, here I have done it as such:
var mouse = {x: 0, y: 0};
After that, simply update the coordinates when the mousemove event fires. Now we remember the position, which means in the future you could actually animate this circle from point to point as it does not rely on the event to actually know the values.
A polyfill for requestAnimationFrame is actually no longer necessary, almost every browser supports it except some older ones.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var mouse = {x: 0, y: 0};
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function circle() {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(mouse.x, mouse.y, 30, 0, Math.PI * 2, true);
ctx.fill();
}
function draw(e) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle();
window.requestAnimationFrame(draw);
}
document.addEventListener('mousemove', function(e) {
mouse.x = e.pageX > mouse.x ? e.pageX : mouse.x;
mouse.y = e.pageY > mouse.y ? e.pageY : mouse.y;
});
window.requestAnimationFrame(draw);
html, body { height: 100%; }
body { overflow: hidden; padding: 0; margin: 0;}
<canvas id="canvas"></canvas>
It might be better to rename some functions, just for future obviousness. I have also learned the hard way, a long time ago, that you should keep your function names in English, mostly because programming happens to be based on English. This way every user on this site can decipher what a function might do, and future developers will be able to debug your code without knowing french. For example, I would rename circle to something like drawCircleAtMousePosition - its a mouthful, but nobody can confuse what this function does.
Another advantage of using a stored variable is that you can do your pos (which is a really bad name for a function - maybe localiseCoordinatesTo(canvas)) right in the onmousemove event, so you never have to think about this at a later point.
Update: Animating
Here is an implementation that uses a very simple linear interpolation to animate the circle from place to place:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// We will need a from value, a to value, and store a time;
var mouse = {from: {x: 0, y: 0}, to: {x: 0, y: 0}, time: Date.now()};
// As well as a duration
var duration = 1000;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function position(){
// This will calculate the position
var time = Date.now(), progress;
if(time > mouse.time + duration)
return mouse.to;
else
progress = (time - mouse.time) / duration;
return {
x: mouse.from.x + (mouse.to.x - mouse.from.x) * progress,
y: mouse.from.y + (mouse.to.y - mouse.from.y) * progress
}
}
function circle() {
ctx.fillStyle = "red";
ctx.beginPath();
var pos = position();
ctx.arc(pos.x, pos.y, 30, 0, Math.PI * 2, true);
ctx.fill();
}
function draw(e) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle();
window.requestAnimationFrame(draw);
}
document.addEventListener('mousemove', function(e) {
// Update FROM to the current position
mouse.from = position();
// Reassign the to values
mouse.to.x = e.pageX > mouse.to.x ? e.pageX : mouse.to.x;
mouse.to.y = e.pageY > mouse.to.y ? e.pageY : mouse.to.y;
// Update the animation start time.
mouse.time = Date.now();
});
window.requestAnimationFrame(draw);
html, body { height: 100%; }
body { overflow: hidden; padding: 0; margin: 0;}
<canvas id="canvas"></canvas>

mousemove event not working like expected in Javascript

I have some code below for the start of a snake game that I'm making using HTML5 canvas. For some reason, the red circle that I'm temporarily using to represent my snake is drawing constantly following the path the mouse moves in. and it uses the food as a starting point. Check it out in your browser, because it's really hard to describe. All I want is for the circle to follow the mouse and leave a small trail that ends and doesn't stay on the canvas. How would I go about doing this. Thanks in advance!
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Snake 2.0</title>
</head>
<style>
</style>
<body>
<div>
<canvas id="canvas" width=500 height=500></canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
makeFood();
function makeFood() {
foods = [];
for (var i = 0; i < 1; i++){
foods.push(new Food());
}
}
function Food() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 10;
}
function drawFood() {
for (var i = 0; i < 1; i++){
foods.push(new Food());
}
for (var i = 0; i < foods.length; i++){
var f = foods[i];
context.beginPath();
var grd = context.createRadialGradient(f.x, f.y, (f.radius - (f.radius - 1)), f.x + 1, f.y + 1, (f.radius));
grd.addColorStop(0, 'red');
grd.addColorStop(1, 'blue');
context.arc(f.x, f.y, f.radius, 0, 2 * Math.PI, true);
context.fillStyle = grd;
context.fill();
}
}
function makePower() {
powers = [];
for (var i = 0; i < 1; i++){
powers.push(new Power());
}
}
function Power() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 8;
}
function drawPower() {
for (var i = 0; i < powers.length; i++){
var p = powers[i];
context.beginPath();
var grd = context.createRadialGradient(p.x, p.y, (p.radius - (p.radius - 1)), p.x + 1, p.y + 1, (p.radius));
grd.addColorStop(0, 'green');
grd.addColorStop(1, 'yellow');
context.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true);
context.fillStyle = grd;
context.fill();
}
}
canvas.addEventListener("mousemove", function(event) {
move(event);
});
function move(e) {
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
var a = e.clientX;
var b = e.clientY;
context.arc(a, b, 20, 0, 2 * Math.PI, true);
context.fillStyle = "red";
context.fill();
}
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
var functions = [drawFood];
var timer = setInterval(function(){
drawFood();
}, 5000);
function stop() {
clearInterval(timer);
}
canvas.addEventListener("click", stop);
//timer = setInterval(start, 1000);
//timer = setInterval(start, 5000);
</script>
</body>
</html>
You could start by adding "context.beginPath();" in your "move" function, before "context.arc(a, b, 20, 0, 2 * Math.PI, true);", line 102-103 in my editor.
function move(e) {
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
var a = e.clientX;
var b = e.clientY;
context.beginPath();
context.arc(a, b, 20, 0, 2 * Math.PI, true);
context.fillStyle = "red";
context.fill();
}
Here is the fiddle : http://jsfiddle.net/sd5hh57b/1/
You should store the positions you move along in an array. Then a new timer should revisit those discs and redraw them in a more faded color each time it ticks, until a disc becomes black. Then it should be removed from that array.
Here is fiddle that does that.
The change in the code starts at canvas.addEventListener("mousemove",... and goes like this:
canvas.addEventListener("mousemove", function(event) {
// Replaced move function by drawDisc function,
// which needs coordinates and color intensity
drawDisc(event.clientX, event.clientY, 0xF);
});
// Array to keep track of previous positions, i.e. the trail
var trail = [];
function drawDisc(x, y, red) {
context.beginPath();
context.arc(x, y, 20, 0, 2 * Math.PI, true);
context.fillStyle = '#' + red.toString(16) + '00000';
context.fill();
// If disc is not completely faded out, push it in the trail list
if (red) {
trail.push({x: x, y: y, red: red});
}
}
// New function to regularly redraw the trail
function fadeTrail() {
var discs = trail.length;
// If there is only one disc in the trail, leave it as-is,
// it represents the current position.
if (discs > 1) {
for (var i = discs; i; i--) {
// take "oldest" disc out of the array:
disc = trail.shift();
// and draw it with a more faded color, unless it is
// the current disc, which keeps its color
drawDisc(disc.x, disc.y, disc.red - (i === 1 ? 0 : 1));
}
}
}
// New timer to fade the trail
var timerFade = setInterval(function(){
fadeTrail();
}, 10);
I think the comments will make clear what this does. Note that the colors of the discs go from 0xF00000 to 0xE00000, 0xD00000, ... , 0x000000. Except the current disc, that one keeps its 0xF00000 color all the time.
The other answers are right :
Use beginPath() at each new arc() to create a new Path and avoid context.fill() considers the whole as a single Path.
Use a trail Array to store your last positions to draw the trail.
But, the use of setTimeout and setInterval should be avoided (and even further the use of multiple ones).
Modern browsers do support requestAnimationFrame timing method, and for olders (basically IE9), you can find polyfills quite easily. It has a lot of advantages that I won't enumerate here, read the docs.
Here is a modified version of your code, which uses a requestAnimationFrame loop.
I also created two offscreen canvases to update your foods and powers, this way they won't disappear at each draw. Both will be painted in the draw function.
I changed the mousemove handler so it only updates the trail array, leaving the drawing part in the draw loop. At each call, it will set a moving flag that will let our draw function know that we are moving the mouse. Otherwise, it will start to remove old trail arcs from the Array.
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var context = canvas.getContext("2d");
// create other contexts (layer like) for your food and powers
var foodContext = canvas.cloneNode(true).getContext('2d');
var pwrContext = canvas.cloneNode(true).getContext('2d');
// a global to tell weither we are moving or not
var moving;
// a global to store our animation requests and to allow us to pause it
var raf;
// an array to store our trail position
var trail = [];
// here we can determine how much of the last position we'll keep at max (can then be updated if we ate some food)
var trailLength = 10;
// your array for the foods
var foods = [];
// a global to store the last time we drawn the food, no more setInterval
var lastDrawnFood = 0;
// start the game
draw();
function makeFood() {
foods.push(new Food());
}
function Food() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 10;
}
function drawFood() {
// clear the food Canvas (this could be done only if we ate some, avoiding the loop through all our foods at each call of this method)
foodContext.clearRect(0, 0, canvas.width, canvas.height);
foods.push(new Food());
for (var i = 0; i < foods.length; i++) {
var f = foods[i];
// draw on the food context
foodContext.beginPath();
foodContext.arc(f.x, f.y, f.radius, 0, 2 * Math.PI, true);
var foodGrd = foodContext.createRadialGradient(f.x, f.y, (f.radius - (f.radius - 1)), f.x + 1, f.y + 1, (f.radius));
foodGrd.addColorStop(0, 'red');
foodGrd.addColorStop(1, 'blue');
foodContext.fillStyle = foodGrd;
foodContext.fill();
}
}
// I'll let you update this one
function makePower() {
powers = [];
for (var i = 0; i < 1; i++) {
powers.push(new Power());
}
}
function Power() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 8;
}
function drawPower() {
pwrContext.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < powers.length; i++) {
var p = powers[i];
var pwrGrd = pwrContext.createRadialGradient(p.x, p.y, (p.radius - (p.radius - 1)), p.x + 1, p.y + 1, (p.radius));
pwrGrd.addColorStop(0, 'green');
pwrGrd.addColorStop(1, 'yellow');
pwrContext.beginPath();
pwrContext.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true);
pwrContext.fillStyle = pwrGrd;
pwrContext.fill();
}
}
// the event object is already passed, no need for an anonymous function here
canvas.addEventListener("mousemove", move);
function move(e) {
// we paused the game, don't update our position
if (!raf) return;
// update the snake
var a = e.clientX - canvas.offsetLeft;
var b = e.clientY - canvas.offsetTop;
trail.splice(0, 0, {
x: a,
y: b
});
// tell our draw function that we moved
moving = true;
}
function draw(time) {
// our food timer
if (time - lastDrawnFood > 5000) {
lastDrawnFood = time;
drawFood();
}
// clear the canvas
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
// draw the food
context.drawImage(foodContext.canvas, 0, 0);
// draw the power
context.drawImage(pwrContext.canvas, 0, 0);
//draw the snake
for (var i = 0; i < trail.length; i++) {
// decrease the opacity
opacity = 1 - (i / trail.length);
context.fillStyle = "rgba(255, 0,0," + opacity + ")";
// don't forget to create a new Path for each circle
context.beginPath();
context.arc(trail[i].x, trail[i].y, 20, 0, 2 * Math.PI, true);
context.fill();
}
// if we're not moving or if our trail is too long
if ((!moving || trail.length > trailLength) && trail.length > 1)
// remove the oldest trail circle
trail.pop();
// we're not moving anymore
moving = false;
// update the animation request
raf = requestAnimationFrame(draw);
}
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
function toggleStop() {
if (!raf) {
// restart the animation
raf = window.requestAnimationFrame(draw);
} else {
// cancel the next call
cancelAnimationFrame(raf);
raf = 0;
}
}
canvas.addEventListener("click", toggleStop);
html, body{margin:0;}
<canvas id="canvas" width=500 height=500></canvas>

Update HTML5 canvas rectangle on hover?

I've got some code which draws a rectangle on a canvas, but I want that rectangle to change color when I hover the mouse over it.
The problem is after I've drawn the rectangle I'm not sure how I select it again to make the adjustment.
What I want to do:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
$('c.[rectangle]').hover(function(this){
this.fillStyle = 'red';
this.fill();
});
You can't do this out-of-the-box with canvas. Canvas is just a bitmap, so the hover logic has to be implemented manually.
Here is how:
Store all the rectangles you want as simple object
For each mouse move on the canvas element:
Get mouse position
Iterate through the list of objects
use isPointInPath() to detect a "hover"
Redraw both states
Example
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
rects = [
{x: 10, y: 10, w: 200, h: 50},
{x: 50, y: 70, w: 150, h: 30} // etc.
], i = 0, r;
// render initial rects.
while(r = rects[i++]) ctx.rect(r.x, r.y, r.w, r.h);
ctx.fillStyle = "blue"; ctx.fill();
canvas.onmousemove = function(e) {
// important: correct mouse position:
var rect = this.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0, r;
ctx.clearRect(0, 0, canvas.width, canvas.height); // for demo
while(r = rects[i++]) {
// add a single rect to path:
ctx.beginPath();
ctx.rect(r.x, r.y, r.w, r.h);
// check if we hover it, fill red, if not fill it blue
ctx.fillStyle = ctx.isPointInPath(x, y) ? "red" : "blue";
ctx.fill();
}
};
<canvas/>
This is a stable code in base of #K3N answer. The basic problem of his code is because when one box is over the another the two may get mouse hover at same time. My answer perfectly solves that adding a 'DESC' to 'ASC' loop.
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
var map = [
{x: 20, y: 20, w: 60, h: 60},
{x: 30, y: 50, w: 76, h: 60}
];
var hover = false, id;
var _i, _b;
function renderMap() {
for(_i = 0; _b = map[_i]; _i ++) {
ctx.fillStyle = (hover && id === _i) ? "red" : "blue";
ctx.fillRect(_b.x, _b.y, _b.w, _b.h);
}
}
// Render everything
renderMap();
canvas.onmousemove = function(e) {
// Get the current mouse position
var r = canvas.getBoundingClientRect(),
x = e.clientX - r.left, y = e.clientY - r.top;
hover = false;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for(var i = map.length - 1, b; b = map[i]; i--) {
if(x >= b.x && x <= b.x + b.w &&
y >= b.y && y <= b.y + b.h) {
// The mouse honestly hits the rect
hover = true;
id = i;
break;
}
}
// Draw the rectangles by Z (ASC)
renderMap();
}
<canvas id="canvas"></canvas>
You may have to track the mouse on the canvas using JavaScript and see when it is over your rectangle and change the color then. See code below from my blog post
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="700" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
var myRect={x:150, y:75, w:50, h:50, color:"red"};
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = myRect.color;
ctx.fillRect(myRect.x, myRect.y, myRect.w, myRect.h);
c.addEventListener("mousemove", function(e){
if ((e.clientX>=myRect.x)&(e.clientX<=myRect.x+myRect.w)&(e.clientY>=myRect.y)&(e.clientY<=myRect.y+myRect.h)){
myRect.color = "green";}
else{
myRect.color = "red";}
updateCanvas();
}, false);
function updateCanvas(){
ctx.fillStyle = myRect.color;
ctx.fillRect(myRect.x, myRect.y, myRect.w, myRect.h);
}
</script>
</body>
</html>
I believe this is a slightly more in-depth answer that would work better for you, especially if you are interested in game design with the canvas element.
The main reason this would work better for you is because it focuses more on an OOP (object orientated programming) approach. This allows for objects to be defined, tracked and altered at a later time via some event or circumstance. It also allows for easy scaling of your code and in my opinion is just more readable and organized.
Essentially what you have here is two shapes colliding. The cursor and the individual point / object it hovers over. With basic squares, rectangles or circles this isn't too bad. But, if you are comparing two more unique shapes, you'll need to read up more on Separating Axis Theorem (SAT) and other collision techniques. At that point optimizing and performance will become a concern, but for now I think this is the optimal approach.
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;
const cx = width / 2;
const cy = height / 2;
const twoPie = Math.PI * 2;
const points = []; // This will be the array we store our hover points in later
class Point {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r || 0;
}
}
class HoverPoint extends Point {
constructor(x, y, r, color, hoverColor) {
super(x, y, r);
this.color = color;
this.hoverColor = hoverColor;
this.hovered = false;
this.path = new Path2D();
}
draw() {
this.hovered ? ctx.fillStyle = this.hoverColor : ctx.fillStyle = this.color;
this.path.arc(this.x, this.y, this.r, 0, twoPie);
ctx.fill(this.path);
}
}
class Cursor extends Point {
constructor(x, y, r) {
super(x, y, r);
}
collisionCheck(points) {
// This is the method that will be called during the animate function that
// will check the cursors position against each of our objects in the points array.
document.body.style.cursor = "default";
points.forEach(point => {
point.hovered = false;
if (ctx.isPointInPath(point.path, this.x, this.y)) {
document.body.style.cursor = "pointer";
point.hovered = true;
}
});
}
}
function createPoints() {
// Create your points and add them to the points array.
points.push(new HoverPoint(cx, cy, 100, 'red', 'coral'));
points.push(new HoverPoint(cx + 250, cy - 100, 50, 'teal', 'skyBlue'));
// ....
}
function update() {
ctx.clearRect(0, 0, width, height);
points.forEach(point => point.draw());
}
function animate(e) {
const cursor = new Cursor(e.offsetX, e.offsetY);
update();
cursor.collisionCheck(points);
}
createPoints();
update();
canvas.onmousemove = animate;
There is one more thing that I would like to suggest. I haven't done tests on this yet but I suspect that using some simple trigonometry to detect if our circular objects collide would preform better over the ctx.IsPointInPath() method.
However if you are using more complex paths and shapes, then the ctx.IsPointInPath() method would most likely be the way to go. if not some other more extensive form of collision detection as I mentioned earlier.
The resulting change would look like this...
class Cursor extends Point {
constructor(x, y, r) {
super(x, y, r);
}
collisionCheck(points) {
document.body.style.cursor = "default";
points.forEach(point => {
let dx = point.x - this.x;
let dy = point.y - this.y;
let distance = Math.hypot(dx, dy);
let dr = point.r + this.r;
point.hovered = false;
// If the distance between the two objects is less then their combined radius
// then they must be touching.
if (distance < dr) {
document.body.style.cursor = "pointer";
point.hovered = true;
}
});
}
}
here is a link containing examples an other links related to collision detection
I hope you can see how easily something like this can be modified and used in games and whatever else. Hope this helps.
Below code adds shadow to canvas circle on hovering it.
<html>
<body>
<canvas id="myCanvas" width="1000" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
</body>
<script>
var canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d"),
circle = [{
x: 60,
y: 50,
r: 40,
},
{
x: 100,
y: 150,
r: 50,
} // etc.
];
// render initial rects.
for (var i = 0; i < circle.length; i++) {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
}
canvas.onmousemove = function(e) {
var x = e.pageX,
y = e.pageY,
i = 0,
r;
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < circle.length; i++) {
if ((x > circle[i].x - circle[i].r) && (y > circle[i].y - circle[i].r) && (x < circle[i].x + circle[i].r) && (y < circle[i].y + circle[i].r)) {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
ctx.shadowBlur = 10;
ctx.lineWidth = 3;
ctx.strokeStyle = 'rgb(255,255,255)';
ctx.shadowColor = 'grey';
ctx.stroke();
ctx.shadowColor = 'white';
ctx.shadowBlur = 0;
} else {
ctx.beginPath();
ctx.arc(circle[i].x, circle[i].y, circle[i].r, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
ctx.shadowColor = 'white';
ctx.shadowBlur = 0;
}
}
};
</script>
</html>
I know this is old, but I am surprised no one has mentioned JCanvas. It adds to the simplicity of animating canvas on events. More documentation here https://projects.calebevans.me/jcanvas/docs/mouseEvents/
<html lang="en">
<head>
<!-- css and other -->
</head>
<body onload="draw();">
<canvas id = "canvas" width="500" height="500" style= border:1px solid #000000;"> </canvas>
<script>
function draw() {
$('canvas').drawRect({
layer: true,
fillStyle:'#333',
x:100, y: 200,
width: 600,
height: 400,
mouseover: function(layer) {
$(this).animateLayer(layer, {
fillStyle: 'green'
}, 1000, 'swing');
}
});
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jcanvas/21.0.1/jcanvas.js" crossorigin="anonymous"></script>
</body>
</html>
Consider this following code:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
c.addEventListener("mouseover", doMouseOver, false);//added event to canvas
function doMouseOver(e){
ctx.fillStyle = 'red';
ctx.fill();
}
DEMO
You could use canvas.addEventListener
var canvas = document.getElementById('canvas0');
canvas.addEventListener('mouseover', function() { /*your code*/ }, false);
It worked on google chrome
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
$(c).hover(function(e){
ctx.fillStyle = 'red';
ctx.fill();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="myCanvas"/>

Adding html content on a moving element in Canvas

How I can add Html content on a moving element in the Canvas, like this one
http://www.html5canvastutorials.com/labs/html5-canvas-harmonic-oscillator/
where I need to display my link or button on the moving block attached to the spring. Generally for static canvas elements we can use Z-index or overlapping techniques, but these don't work in this case.
Any solutions ?
Check if the following script works:
<script src="http://www.html5canvastutorials.com/libraries/kinetic2d-v1.0.3.js">
</script>
<script>
var button = {
x: 0,
y: 0,
size: 16,
width: 0,
height: 0,
padding: 4,
hover: false,
text: "Click Me",
onclick: function (e) {
// put your event handler code here
}
};
function drawSpring(canvas, context){
context.beginPath();
context.moveTo(0, 0);
for (var y = 0; y < 200; y++) {
// Sine wave equation
var x = 30 * Math.sin(y / 9.05);
context.lineTo(x, y);
}
}
function drawWeight(canvas, context, y){
var size = 100;
context.save();
context.fillStyle = "red";
context.fillRect(-size / 2, 0, size, size);
context.restore();
canvas.fillText(button.text, 0, 0);
button.x = ((canvas.width - button.width) / 2) - button.padding;
button.y = (y + (size - button.height) / 2) - button.padding;
}
window.onload = function(){
var kin = new Kinetic_2d("myCanvas");
var canvas = kin.getCanvas();
var context = kin.getContext();
context.font = button.size + "px Verdana";
context.textAlign = "center";
context.textBaseline = "top";
button.width = 2 * button.padding + context.measureText(button.text);
button.height = 2 * button.padding + button.size;
var theta = 0;
var curleft = 0;
var curtop = 0;
var obj = canvas;
do {
curleft += object.offsetLeft;
curtop += object.offsetTop;
} while (obj = obj.offsetParent);
canvas.addEventListener("mousemove", function (e) {
context.beginPath();
context.rect(button.x, button.y, button.width, button.height);
button.hover = context.isPointInPath(e.pageX - curleft, e.pageY - curtop);
}, false);
canvas.addEventListener("click", function (e) {
if (button.hover) button.onclick(e);
}, false);
kin.setDrawStage(function(){
theta += this.getTimeInterval() / 400;
var scale = 0.8 * (Math.sin(theta) + 1.3);
this.clear();
context.save();
context.translate(canvas.width / 2, 0);
context.save();
context.scale(1, scale);
drawSpring(canvas, context);
context.restore();
context.lineWidth = 6;
context.strokeStyle = "#0096FF"; // blue-ish color
context.stroke();
context.translate(0, 200 * scale);
drawWeight(canvas, context, 200 * scale);
context.restore();
});
kin.startAnimation();
};
</script>

Categories

Resources