簡體   English   中英

無法更改HTML 5畫布中的線寬

[英]Cannot change line width in HTML 5 canvas

我建立了一個非常簡單的應用程序,通過單擊“ Add按鈕可以在圖像中繪制矩形。 但是,無論我更改了canvas stroke什么屬性,這些屬性都保持不變。

在該示例中, 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> 

您正在使用CSS設置位圖的大小。 這將僅適用於元素本身,而不適用於位圖。 位圖的默認大小為300x150,這是您看到的被拉伸的大小。

設置元素的屬性以影響位圖,例如:

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

更新小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM