2015-06-09 25 views
-1

我构建了一个非常简单的应用程序,通过单击Add按钮在图像中绘制矩形。但是,不管strokecanvas我改变了哪些属性,属性都保持不变。无法更改HTML 5画布中的线宽

在该示例中,context.lineWidth已被设置为1。但是,矩形,点击按钮Add后拉伸,实际上有宽得多的线宽度,并且还具有一些透明度(我想要的线成为固体,并在不透明所有)。

任何人都可以在这里提供一些帮助?我的代码Fiddle

var img = $('#sourceImage'); 
 
var addButton = $('#addButton'); 
 
addButton.offset({ 
 
    top: img.offset().top + img.height() + 10 
 
}); 
 

 
var boundingBoxId = 'IMG00001_01'; 
 

 
addButton.click(function() { 
 
    console.log(boundingBoxId); 
 
    $('<canvas>').attr({ 
 
     id: boundingBoxId 
 
    }).css({ 
 
     width: img.width() + 'px', 
 
     height: img.height() + 'px', 
 
     position: 'absolute' 
 
    }).appendTo('#drawArea'); 
 

 
    var canvas = document.getElementById(boundingBoxId); 
 
    var context = canvas.getContext('2d'); 
 
    context.strokeStyle = 'red'; 
 
    context.rect(0, 0, 50, 50); 
 
    context.lineWidth = 1; 
 
    context.stroke(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="drawArea"> 
 
    <img id="sourceImage" src="http://www.sixt.com/uploads/pics/bmw_5_sixt-car_rental-B.png" style="position: absolute; border: 1px solid #000000" /> 
 
</div> 
 
<button id="addButton">Add</button>

回答

2

您正在使用CSS来设置位图的大小。这只适用于元素本身,而不适用于位图。位图的默认大小为300x150,这是您看到的延伸。

设置元素的属性影响的位图,如:

$('<canvas>').attr({ 
    id: boundingBoxId 
}).attr({ 
    width: img.width(),  // important: attributes affect bitmap 
    height: img.height() 
}).css({ 
    position: 'absolute'  // affects element 
}).appendTo('#drawArea'); 

Updated fiddle

+0

我明白了。非常感谢!我是HTML 5和Javascript的新手。你的回答今天帮助我很多! – mintaka

+0

嗨,我还有一个问题。修改代码后,该行仍然有点透明(如在更新的提琴中;它似乎只发生在线宽为1时)。我可以知道它为什么透明吗?我试图设置Alpha通道,但没有找到任何运气。 – mintaka

+0

@mintaka这是由于子像素。画布将网格中的像素居中,可以像这样抵消0.5像素:http://jsfiddle.net/cqy12b5m/12/ – K3N