1

I'm trying to come up with a proof-of-concept on how to use canvas to create different length items (in this case a bike stem).

My idea is to provide 2 svgs (fragments) of the bike stem, then use a canvas line to connect them. I like this concept, but it feels very clunky and I'm unsure if this is sustainable. Ideally, I'd be able to extend this line, which would then extend the canvas, thus adjusting my drawn line.

  document.addEventListener("DOMContentLoaded",() => {
    const drawFragment = (imgsrc, xcord, ycord) => {
      let img = newImage();
      img.onload = () => {
        ctx.drawImage(img, xcord, ycord);
      }
       img.src = imgsrc;
    };

    const drawConnector = (ctx, xstart, ystart, xend, yend,) => {
      ctx.beginPath();
      ctx.moveTo(xstart, ystart);
      ctx.lineTo(xend, yend);
      ctx.stroke();
    };

    const canvas = document.getElementById('canvas1');
    const ctx = canvas.getContext('2d');
    drawFragment('svgs/stem-fragment-01.svg, 0, 0);
    drawFragment('svgs/stem-fragment-02.svg, 400, 0);
    drawConnector(ctx, 209, 33, 400, 36);
    drawConnector(ctx, 209, 169, 400, 159);
  });

Which basically creates this (redlines are the drawn canvas elements)

enter image description here

Like I said, this feels very clunky and I'm wondering if i'm missing some out of the box canvas solution? The thought of mapping out the points one by one, seems like it will be more trouble than it's worth in the long run.

Here are the fragment svgs as well

Stem Fragment 1: https://pastebin.com/u0E4Nq6r

Stem Fragment 2: https://pastebin.com/71WTfS4y

4
  • 2
    Wouldn't it be easier to use SVG instead of canvas for this?
    – Kosh
    Commented Jan 30 at 5:21
  • @Kosh, potentially.. Do you mean as to keep the svg images intact, and then find a way to grab the specific lines I need to modify? I originally thought canvas could work because I've seen examples where your'e able to draw to a direct point, but like I said, upon testing, it feels clunky. Commented Jan 30 at 5:26
  • Yes I agree with Kosh use one SVG for all three components. Or just HTML. Make a wrapper element set to relative position and place everything inside with position absolute. That's it. Commented Jan 31 at 12:55
  • Yep, this was the answer. I'm basically using a flexbox wrapper, and my svgs of the front/rear of the stem go on either side. Then using absolute positioning, I put coord divs where I want and use positioning to draw to them. Thanks for the suggestion! Here's my rough concept, I got the idea of drawing from the coord divs from another S/o answer: jsfiddle.net/u7vw65ga/7 Commented Jan 31 at 22:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.