我在页面中有一个画布,后面有一些文字:
<canvas id="myCanvas" width="800" height="160"></canvas>
<p>Some text after the canvas</p>
我使用JavaScript绘制点/线。这个很简单。
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var drawing = false;
canvas.onmousedown = function(e){
if( !drawing )
{
drawing = true;
ctx.beginPath();
}
}
canvas.onmousemove = function(e){
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
if( drawing )
{
ctx.lineTo(x,y);
ctx.stroke();
}
}
canvas.onmouseup = function(e){
drawing = false;
}
canvas.onmouseout = function(e){
drawing = false;
}
如果我点击画布并按住,我可以在画布中移动鼠标并绘制线条。大!但是,如果我继续按住并将鼠标从画布上移开并超过<p>
文本,我将最终突出显示该文本。不太好!我注意到在某些浏览器中不会发生这种情况。这是我测试过的列表:
我的问题:如何防止突出问题发生?
答案 0 :(得分:4)
您可以选择onDrag上的文本选择:
演示:http://jsfiddle.net/zb2soupb/
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
canvas.onmousemove = function(e){
// Dissable text selection
document.body.classList.add('unselectable')
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
if( drawing )
{
ctx.lineTo(x,y);
ctx.stroke();
}
}
canvas.onmouseup = function(e){
drawing = false;
document.body.classList.remove('unselectable')
}
答案 1 :(得分:0)
我认为最好的答案是在所有画布鼠标事件处理程序中调用“ e.preventDefault()”,例如:
canvas.onmousedown = function(e){
e.preventDefault(); // <-- this
if( !drawing )
{
drawing = true;
ctx.beginPath();
}
}