我尝试使用鼠标事件动态绘制svg行覆盖现有html文本。它适用于Firefox,但与IE9崩溃。使用ie9绘制线条,但仅限于文档的未占用部分。当鼠标指针在html文本上移动时,当鼠标指针从一个箭头变为另一个时,你可以告诉ie9。以下是我的svg代码:
function SVG( docframe, objectType, color ){ this.svgID = "svg" + canvasCount++;
var height = parseFloat( docframe.style.height ) * 10;
var width = parseFloat( docframe.style.width ) * 10;
var svg = document.createElementNS( "http://www.w3.org/2000/svg", "svg" );
svg.setAttributeNS( "http://www.w3.org/2000/xmlns/", "xmlns:xlink",
SVG.xlinkns );
svg.color = color;
svg.setAttribute( 'width', width );
svg.setAttribute( 'height', height );
svg.setAttribute( "viewBox", "0 0 " + width + " " + height );
svg.style.width = width + "px";
svg.style.height = height + "px";
svg.setAttribute( 'id', this.svgID );
svg.style.overflow = 'visible';
svg.style.position = 'absolute';
svg.tabIndex = svg.style.zIndex = 10;
this.svg = svg;
//append canvas to divf
docframe.appendChild( svg );
//Define Canvas functions
this.svg.onmousedown = function ( e )
{
var mouseX = 0;
var mouseY = 0;
coordinates.splice( 0, coordinates.length );
paint = true;
//if IE
if ( navigator.appName == "Microsoft Internet Explorer" )
{
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else
{
mouseX = ( e.layerX - dragOffsets.left );
mouseY = ( e.layerY - dragOffsets.top );
}
paint = true;
addClick( mouseX, mouseY );
redraw( this );
}
this.svg.onmousemove = function ( e )
{
if ( paint )
{
var mouseX = 0;
var mouseY = 0;
//if IE
if ( navigator.appName == "Microsoft Internet Explorer" )
{
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else
{
mouseX = ( e.layerX - dragOffsets.left );
mouseY = ( e.layerY - dragOffsets.top );
}
addClick( mouseX, mouseY);
redraw( this );
}
}
this.svg.onmouseover = function ( e )
{
if ( paint )
{
var mouseX = 0;
var mouseY = 0;
//if IE
if ( navigator.appName == "Microsoft Internet Explorer" )
{
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else
{
mouseX = ( e.layerX - dragOffsets.left );
mouseY = ( e.layerY - dragOffsets.top );
}
addClick( mouseX, mouseY);
redraw( this );
}
}
this.svg.onmouseup = function ( e )
{
paint = false;
}
}
var paint;
var coordinates = new Array();
function MapPoints( x, y )
{
this.x = x;
this.y = y;
}
function addClick( x, y )
{
if ( coordinates )
{
var mapPoints = new MapPoints( x, y );
coordinates.push( mapPoints );
}
}
function redraw( svg)
{
if ( coordinates )
{
var coorlength = coordinates.length - 1;
if ( coorlength >= 1 )
{
var obj = document.createElementNS( 'http://www.w3.org/2000/svg', 'line' );
obj.setAttribute( 'x1', coordinates[coorlength - 1].x );
obj.setAttribute( 'x2', coordinates[coorlength].x );
obj.setAttribute( 'y1', coordinates[coorlength - 1].y );
obj.setAttribute( 'y2', coordinates[coorlength].y );
obj.setAttribute( 'stroke', svg.color );
obj.setAttribute( 'stroke-width', 5 );
svg.appendChild( obj );
}
}
}