Just use ctx.create.rect() instead of ctx.rect() (etc) and an interactive "canvas object" will be returned.
(no need to write Rect, Sprite (etc) classes - all drawing methods are supported automatically :smile:)
// ...create canvas, and get the 2D context as `ctx`
const myStar = ctx.create.star(x, y, radius, numOfSides, degrees);
// update its properties
myStar.update(x, y, radius, numOfSides, degrees);
// draw it with the given styles
myStar.draw({
strokeStyle: myStar.hover ? 'red' : 'orange',
fillStyle: myStar.clicked ? 'yellow' : 'lightgreen',
});
Customisation
Optionally interact with the canvas inside "mousemove", "mousedown", "mouseup" event handlers:
// update a toolip with object info on hover and click
const tooltip = document.querySelector('.tooltip');
ctx.canvas.addEventListener('mousemove', event => {
// clear tooltip
tooltip.innerHTML = ``;
// if we are hovering on an object in the canvas
if (ctx.hoverObj) {
tooltip.innerHTML = `
<br> Mouse x,y: ${event.offsetX}, ${event.offsetY}
<br> Object id: ${ctx.hoverObj.id}
<br>Object props: ${ctx.hoverObj.props}
`;
}
}, false);
ctx.canvas.addEventListener('mousedown', event => {
if (ctx.hoverObj) tooltip.innerHTML += `<br>Clicked`;
}, false);
Example
See examples/usage-Ctx-interactive.html for a complete example so far.
Description
This PR adds way of doing basic "interactive" canvas stuff:
Changes
Ctx
drawing methods)Usage
Just use
ctx.create.rect()
instead ofctx.rect()
(etc) and an interactive "canvas object" will be returned.(no need to write
Rect
,Sprite
(etc) classes - all drawing methods are supported automatically :smile:)Customisation
Optionally interact with the canvas inside "mousemove", "mousedown", "mouseup" event handlers:
Example
See examples/usage-Ctx-interactive.html for a complete example so far.
Hover over the square, or click the star.