简体   繁体   中英

Cannot change line width in HTML 5 canvas

I build a very simple app to draw rectangles in an image by clicking an Add button. However, no matter what properties for stroke in canvas I changed, the properties remain the same.

In that example, context.lineWidth has been set to 1. But the rectangle, drawn after clicking the Add button, actually have a much wider line width and also with some transparency (I want the line to be solid and not transparent at all).

May anyone offer some help here?

Here is my code in 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> 

You are using CSS to set size of the bitmap. That will only apply to the element itself, not the bitmap. The bitmaps' default size is 300x150 which is what you see gets stretched.

Set the attributes of the element to affect the bitmap, like:

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

Updated fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM