简体   繁体   中英

Remove canvas rectangle border on mouseout

Let's say I create a rectangle on the canvas like so...

var c = document.createElement("canvas");
document.body.appendChild(c);
var ctx = c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx.fillText('hover mouse here', 60, 60);

c.addEventListener('mouseover', function() {
    ctx.stroke();
});

Then, when you move your mouse over the text, the border appears around the rectangle. But let's say I wanted the border to then disappear after the mouse leaves the canvas area. Do I need to redraw the entire rectangle or is there an easier way to remove the border?

This is just a simple example. My actual canvas contains several drawings in the rectangle, so it would be a pain to have to redraw it every time. Just curious if there's a simpler way.

I already tried style attributes but that doesn't work.

Here's a fiddle of the above code: http://jsfiddle.net/wqbrnm0o/

The usual pattern used to make changes to canvas is to erase the entire canvas and redraw all the desired contents. Canvas is fast enough to handle most redraws. So you would draw the stroke over your rect on mouseover and you would erase & redraw all content without the stroke on mouseout.

If you still feel the need to retain the content, you could create a second canvas overlaying the first canvas.

On mouseover, you draw only the "highlight" stroke on the top canvas.

On mouseout, you can simply clear the top canvas. The bottom canvas with all your other content will be unaffected.

You can set the CSS pointer-events:none; property on the top canvas so the bottom canvas receives all the mouse events.

You can also make a second event on mouseleave where you stroke a new rectangle ontop of the old one with a white stroke color.

 var c = document.createElement("canvas"); document.body.appendChild(c); var ctx = c.getContext("2d"); ctx.rect(20, 20, 150, 100); ctx.fillText('hover mouse here', 60, 60); c.addEventListener('mouseover', function() { ctx.rect(20, 20, 150, 100); ctx.strokeStyle="#000000"; ctx.stroke(); }); c.addEventListener('mouseleave', function() { ctx.rect(20, 20, 150, 100); ctx.strokeStyle="#ffffff"; ctx.stroke(); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM