猿问

如何使用打字稿翻译canvas html中的六边形

我在 html 的画布上画了一个六边形,当我使用翻译方法时,我想翻译画布中的六边形,它不会翻译六边形,但当我翻译时,当我使用矩形时,它会翻译。

var canvas:HTMLCanvasElement = document.getElementById("myCanvas"); var context:CanvasRenderingContext2D = canvas.getContext("2d");

var x  =  300;

var y =  100;


context.beginPath();

context.moveTo(x, y);

x = x + 120;

y = y + 100;

context.lineTo(x, y);  


y = y + 120;

context.lineTo(x, y); 


x = x - 125;

y = y + 100;

context.lineTo(x, y); 


x = x - 125;

y = y - 100;

context.lineTo(x, y); 


y = y - 120;

context.lineTo(x, y); 


x = x + 130;

y = y - 100;

context.lineTo(x, y);

context.strokeStyle = "red";

context.lineWidth = 4;  

context.fillStyle = "blue";

context.fill(); 


context.translate(400,400);

context.fillStyle = "blue";

context.fill(); 

context.save(); 


context.fillRect(10, 10, 100, 50);

    context.translate(70, 70);

    context.fillRect(10, 10, 100, 50);

编辑1: 根据@helder给出的答案,我已经进行了更改,但翻译不起作用


function hexagon(x:number, y:number, r:number, color:string) {

  context.beginPath();

  var angle = 0

  for (var j = 0; j < 6; j++) {

    var a = angle * Math.PI / 180

    var xd = r * Math.sin(a)

    var yd = r * Math.cos(a)

    context.lineTo(x + xd, y + yd);

    angle += 360 / 6

  }

  context.fillStyle = color;

  context.fill();

  context.translate(70,70);

  context.fill();

}


hexagon(100, 100, 50, "red")


慕侠2389804
浏览 85回答 1
1回答

ABOUTYOU

我会尝试创建一个绘制六边形的函数,这样您就不必使用翻译。见下文c = document.getElementById("canvas");context = c.getContext("2d");function hexagon(x, y, r, color) {&nbsp; context.beginPath();&nbsp; var angle = 0&nbsp; for (var j = 0; j < 6; j++) {&nbsp; &nbsp; var a = angle * Math.PI / 180&nbsp; &nbsp; var xd = r * Math.sin(a)&nbsp; &nbsp; var yd = r * Math.cos(a)&nbsp; &nbsp; context.lineTo(x + xd, y + yd);&nbsp; &nbsp; angle += 360 / 6&nbsp; }&nbsp; context.fillStyle = color;&nbsp; context.fill();}hexagon(50, 50, 30, "red")hexagon(40, 40, 10, "blue")hexagon(60, 60, 10, "lime")<canvas id=canvas >这是一个细分function hexagon(x, y, r, color)它以六边形 (&nbsp;x,y) 为中心、半径 (&nbsp;r) 和颜色我们遍历六个顶点并绘制线条计算只是一点三角函数,没什么特别的这样我们就可以在任何我们想要的位置绘制六边形。您可以轻松地重构相同的函数来绘制八边形或其他多边形。这是这些六边形的动画版本c = document.getElementById("canvas");context = c.getContext("2d");delta = 0function hexagon(x, y, r, color) {&nbsp; context.beginPath();&nbsp; var angle = 0&nbsp; for (var j = 0; j < 6; j++) {&nbsp; &nbsp; var a = angle * Math.PI / 180&nbsp; &nbsp; var xd = r * Math.sin(a)&nbsp; &nbsp; var yd = r * Math.cos(a)&nbsp; &nbsp; context.lineTo(x + xd, y + yd);&nbsp; &nbsp; angle += 360 / 6&nbsp; }&nbsp; context.fillStyle = color;&nbsp; context.fill();}function draw() {&nbsp; context.clearRect(0, 0, c.width, c.height)&nbsp; var xd = 10 * Math.sin(delta)&nbsp; var yd = 10 * Math.cos(delta)&nbsp; hexagon(50 - xd, 50 - yd, 30, "red")&nbsp; hexagon(40 + xd, 40 + yd, 10, "blue")&nbsp; delta += 0.2}setInterval(draw, 100);<canvas id=canvas>正如你所看到的,不需要使用翻译
随时随地看视频慕课网APP

相关分类

Html5
我要回答