Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

draw a rectangle on canvas on pointermove


    let isCon = false;
    let cur = 0;
    const shapes = [];
    const updateFrame = () => {
      shapes.forEach((el) => {
        context.strokeRect(el.x1, el.y1, el.x2 - el.x1, el.y2 - el.y1);
      });
    }

    canvas.addEventListener("pointerdown", function(e){
      isCon = true;
      shapes.push({
        x1: e.clientX - canvas.offsetLeft,
        y1: e.clientY - canvas.offsetTop,
        x2: e.clientX - canvas.offsetLeft,
        y2: e.clientY - canvas.offsetTop,
      });
      context.save();
    });

    canvas.addEventListener("pointermove", function(e){
      if (isCon) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        shapes[cur].x2 = e.clientX - canvas.offsetLeft;
        shapes[cur].y2 = e.clientY - canvas.offsetTop;
        requestAnimationFrame(updateFrame);
      }
    });

    canvas.addEventListener("pointerup", function(){
      isCon = false;
      cur += 1;
    });
 
PREVIOUS NEXT
Tagged: #draw #rectangle #canvas #pointermove
ADD COMMENT
Topic
Name
5+1 =