Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make HTML5 Canvas area unselectable without Javascript

Tags:

html

css

canvas

An app I am making has tabs that use an HTML5 canvas as a backing (they are rounded like chrome tabs, which can't be done through border radius or conventional HTML). However, when someone double clicks on things around the tabs, it highlights the entire canvas area.

// i've tried:
canvas { outline: none; }

// and
canvas { -moz-user-select: none /* etc */ }

// to no avail.

The only solutions I can find on the web is to use JS and event bind each damn canvas with things like:

canvas.onselectstart = function () { return false; }

Then we have to get into unbinding events, etc. etc. and I have these tabs all over my app.

Is there any one shot solution so I don't have to get into this?

UPDATE

To humor CBroe:

enter image description here

and the problem:

enter image description here

SOLVED

pbebbl solved it, by calling a user-select: none on the parent element of the canvas.

like image 620
dthree Avatar asked Jul 29 '26 13:07

dthree


2 Answers

If you do not need to support IE9, then you can indeed use user-select (you'll need prefixes for each of the browsers: -ms-, -moz-, and -webkit-). It's possible the reason that the selection is still appearing is that a higher-level element than you think is selected. Example:

<body>
<div id="wrapper">
    <div id="content">
        <div id="richUI">
            <canvas id="navigationTabs">

If you're doing it to "navigationTabs", try it for "richUI" - or higher.

like image 150
Katana314 Avatar answered Aug 01 '26 04:08

Katana314


It depends on your set up but you could try pointer-events — it's only supported in the more recent of browsers however:

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

canvas { pointer-events: none; }

Obviously this will cause problems if your expecting to trap any mouse events directly on the canvas layers themselves.

update

Hmm. Well it really depends on your markup to what different things you could try, if you posted some of that into your answer it would help. Another guess, which would specifically target the issue which is to block the ondblclick event — but that wouldn't prevent selections occuring by other means.

<body ondblclick="return false">

Also with regard to @Katana314's answer, you may need to disable the selection on the element that wraps the canvas element, rather than target the canvas element directly, for example:

<div class="canvas-wrapper">
  <canvas />
</div>

And then use:

.canvas-wrapper { -moz-user-select: none; }

That may work.

like image 26
Pebbl Avatar answered Aug 01 '26 05:08

Pebbl