how to allow the user to select different pen thickness for the lines, eg. triangle, circle, square?

Dani AI

Generated

asked about letting users pick pen thickness for shapes; was on the right track about applying a stored width to your drawing code. Below is a practical HTML5/canvas approach that shows how to apply a chosen thickness, keep the preview crisp on high-DPI screens, and avoid common gotchas.

<!-- HTML -->
<input id="thickness" type="range" min="1" max="50" value="4">
<canvas id="c" style="width:360px;height:120px;"></canvas>

<!-- JS -->
const c = document.getElementById('c');
const ctx = c.getContext('2d');
const range = document.getElementById('thickness');

function fitCanvas(){
  const dpr = window.devicePixelRatio || 1;
  c.width = Math.floor(c.clientWidth * dpr);
  c.height = Math.floor(c.clientHeight * dpr);
  ctx.setTransform(dpr,0,0,dpr,0,0); // draw in CSS pixels
}
window.addEventListener('resize', fitCanvas);
fitCanvas();

range.addEventListener('input', redraw);
function redraw(){
  const w = parseFloat(range.value);
  ctx.clearRect(0,0,c.width, c.height);
  ctx.lineWidth = w;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';

  // circle
  ctx.beginPath(); ctx.arc(60,60,40,0,Math.PI*2); ctx.stroke();

  // square
  ctx.strokeRect(140,20,80,80);

  // triangle
  ctx.beginPath(); ctx.moveTo(260,100); ctx.lineTo(220,20); ctx.lineTo(300,20); ctx.closePath(); ctx.stroke();
}
redraw();

Troubleshooting and tips: lineWidth is in device pixels, so scale the backing store using devicePixelRatio (as shown) to avoid blurry strokes. Call redraw() after changing width; set lineJoin/lineCap to control how thick corners and ends look (use "round" for smoother shapes). If 1-pixel hairlines look fuzzy, try drawing on half-pixel offsets only for exact 1px strokes or rely on the DPR scaling above.

Extra refinements: store the last choice in localStorage for persistence, expose keyboard shortcuts for accessibility, and if you use SVG instead of canvas set the stroke-width attribute on the element. These small details make the thickness control feel polished and predictable.

On your form you will need a drop down list, textbox or slider control to accept the pen width as input from the user. Save this width to a variable and then when you are creating the pen use that variable to set the width.

float width = // input from the user
Pen blackPen = New Pen(Color.FromArgb(255, 0, 0, 0), width)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.