Home > Blockchain >  Edit lineTo points (in canvas)
Edit lineTo points (in canvas)

Time:02-18

I want to move lineTo points.
How to do it?
I'm new to Canvas.
I'll give an example with Path.

This is my example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
var line = ctx.lineTo(300, 100);
ctx.lineTo(70, 100);
ctx.lineTo(20, 20);
ctx.fillStyle = "red";
ctx.fill();
setTimeout(function() {
  /*
            I want something like this:
            line.editpoints(300, 150);
            */
}, 3000);
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>

CodePudding user response:

Well, canvas as the name suggests, is a canvas (just like in paintings). You can draw on it, but you cannot move things on it as it is not "dynamic".

What you can do, though, is clear it and then draw on top at a different location.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

function clearContext(ctx) {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawTriangle(offsetX = 0, offsetY = 0) {
  ctx.beginPath();
  ctx.moveTo(offsetX   20, offsetY   20);
  var line = ctx.lineTo(offsetX   300, offsetY   100);
  ctx.lineTo(offsetX   70, offsetY   100);
  ctx.lineTo(offsetX   20, offsetY   20);
  ctx.fillStyle = "red";
  ctx.fill();
}
drawTriangle();

setTimeout(function() {
  clearContext(ctx);
  drawTriangle(50, 50);
}, 3000);
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;"></canvas>

  • Related