Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking inside canvas element selects text

I have a canvas element in my HTML document. When I click inside of the canvas multiple times, it selects part of my <h1> element's text, which is before the <canvas> tag. Is there a way to stop this from happening? I am guessing there is a JavaScript solution.

like image 675
Tim Cooper Avatar asked Sep 26 '10 20:09

Tim Cooper


People also ask

How do you add text in canvas elements?

To add a text to the HTML <canvas> element, you need to use the fillText() or strokeText() methods, or you can use the combination of the two. You can also give color to your text, define the font and size, and even add gradients.

How do I access the elements in canvas?

The first line in the script retrieves the node in the DOM representing the <canvas> element by calling the document. getElementById() method. Once you have the element node, you can access the drawing context using its getContext() method.

What is the canvas element used for?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.


1 Answers

Returning false in an event stops the standard event from happening:

document.getElementById('canvas').onmousedown = function(){
  return false;
};

Edit: I just found out that text selection is done before onclick is fired, a better option is onmousedown.

like image 97
Harmen Avatar answered Sep 22 '22 02:09

Harmen